'use client'

import { Button } from "@/shared/components/ui/button"
import { FieldGroup, Field, FieldLabel, FieldDescription, FieldError } from "@/shared/components/ui/field"
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/shared/components/ui/input-otp"
import { valibotResolver } from "@hookform/resolvers/valibot"
import { Controller, useForm } from "react-hook-form"
import { useTransition } from "react"
import { HTTPError } from "ky"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { resendCode } from "../api/resend-code"
import { Spinner } from "@/shared/components/ui/spinner"
import { MailCheckIcon, RotateCcwIcon } from "lucide-react"
import { ApiErrorResponse } from "@/shared/api/instance"
import { verifyEmail } from "../api/verify-email"
import { verifyEmailSchema, type VerifyEmailSchema } from "../schemas/verify-email"

export const VerifyEmailForm = () => {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()
  const form = useForm<VerifyEmailSchema>({
    defaultValues: {
      otp: ''
    },
    mode: 'onBlur',
    resolver: valibotResolver(verifyEmailSchema)
  })

  const onSubmit = (data: VerifyEmailSchema) => {
    startTransition(async () => {
      try {
        const res = await verifyEmail({ body: data })
        toast.success(res.message)
        router.push('/app')
      } catch (error) {
        if (error instanceof HTTPError) {
          const data = await error.response.json<ApiErrorResponse>()
          toast.error(data.message)
        }
      }
    })
  }

  return (
    <form onSubmit={form.handleSubmit(onSubmit)}>
      <FieldGroup>
        <Controller
          control={form.control}
          name="otp"
          render={({ field, fieldState }) => (
            <Field data-invalid={fieldState.invalid}>
              <FieldLabel className="sr-only" htmlFor={field.name}>
                Код подтверждения
              </FieldLabel>
              <InputOTP {...field} maxLength={6} id={field.name}>
                <InputOTPGroup className='mx-auto gap-2.5 *:data-[slot=input-otp-slot]:rounded-md *:data-[slot=input-otp-slot]:border'>
                  <InputOTPSlot index={0} />
                  <InputOTPSlot index={1} />
                  <InputOTPSlot index={2} />
                  <InputOTPSlot index={3} />
                  <InputOTPSlot index={4} />
                  <InputOTPSlot index={5} />
                </InputOTPGroup>
              </InputOTP>
              {fieldState.invalid && (
                <FieldError className='text-center' errors={[fieldState.error]} />
              )}
              <FieldDescription className='text-center'>
                Введите 6-ти значный код подтверждения
              </FieldDescription>
            </Field>
          )}
        />
        <Field orientation='responsive'>
          <Button
            type="button"
            onClick={() => {
              startTransition(async () => {
                const res = await resendCode() as { message: string }
                toast.info(res.message)
              })
            }}
            variant='secondary'
            disabled={isPending}
          >
            Отправить еще раз
            {isPending ? <Spinner /> : <RotateCcwIcon />}
          </Button>
          <Button type='submit' disabled={isPending}>
            Подтвердить
            {isPending ? <Spinner /> : <MailCheckIcon />}
          </Button>
        </Field>
      </FieldGroup>
    </form>
  )
}