"use client"

import { useState } from "react"
import { Loader2Icon } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/src/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/src/components/ui/dialog"
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/src/components/ui/input-otp"
import { useVerifyPhoneOtpMutation } from "@/src/state/auth"
import { extractErrorMessage } from "./utils"

interface PhoneOtpDialogProps {
  open: boolean
  onOpenChange: (v: boolean) => void
  phoneNumber: string
}

export function PhoneOtpDialog({ open, onOpenChange, phoneNumber }: PhoneOtpDialogProps) {
  const [otp, setOtp] = useState("")
  const [error, setError] = useState<string | null>(null)
  const [verifyPhoneOtp, { isLoading }] = useVerifyPhoneOtpMutation()

  const handleVerify = async () => {
    if (otp.length !== 6) return
    setError(null)
    try {
      await verifyPhoneOtp({ phoneNumber, otpCode: otp }).unwrap()
      toast.success("Numéro de téléphone vérifié avec succès")
      onOpenChange(false)
      setOtp("")
    } catch (err) {
      setError(extractErrorMessage(err, "Code invalide. Veuillez réessayer."))
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-sm">
        <DialogHeader>
          <DialogTitle>Vérifier le numéro de téléphone</DialogTitle>
          <DialogDescription>
            Un code a été envoyé au{" "}
            <span className="font-medium text-foreground">{phoneNumber}</span>. Saisissez-le ci-dessous.
          </DialogDescription>
        </DialogHeader>
        <div className="flex flex-col items-center gap-4 py-2">
          <InputOTP maxLength={6} value={otp} onChange={setOtp} disabled={isLoading}>
            <InputOTPGroup>
              <InputOTPSlot index={0} />
              <InputOTPSlot index={1} />
              <InputOTPSlot index={2} />
              <InputOTPSlot index={3} />
              <InputOTPSlot index={4} />
              <InputOTPSlot index={5} />
            </InputOTPGroup>
          </InputOTP>
          {error && <p className="text-xs text-destructive text-center">{error}</p>}
          <Button className="w-full" disabled={otp.length !== 6 || isLoading} onClick={handleVerify}>
            {isLoading && <Loader2Icon className="animate-spin" />}
            Confirmer
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
