'use client'

import { Button } from '@/shared/components/ui/button'
import { Field, FieldLabel, FieldGroup, FieldError } from '@/shared/components/ui/field'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@/shared/components/ui/input-group'
import { IdCardIcon, SaveIcon } from 'lucide-react'
import { useTransition } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { valibotResolver } from '@hookform/resolvers/valibot'
import { Spinner } from '@/shared/components/ui/spinner'
import { useEditFullname } from '../hooks/use-edit-fullname'
import { toast } from 'sonner'
import { editFullnameSchema, type EditFullnameSchema } from '../schemas/edit-fullname'
import { HTTPError } from 'ky'
import { ApiErrorResponse } from '@/shared/api/instance'

interface EditFullnameFormProps {
  fullname?: string
}

export const EditFullnameForm = ({ fullname }: EditFullnameFormProps) => {
  const [isPending, startTransition] = useTransition()
  const { mutateAsync } = useEditFullname()
  const form = useForm<EditFullnameSchema>({
    defaultValues: {
      fullname: fullname ?? ''
    },
    mode: 'onBlur',
    resolver: valibotResolver(editFullnameSchema)
  })

  const onSubmit = (data: EditFullnameSchema) => {
    startTransition(async () => {
      try {
        const res = await mutateAsync({ body: data });
        toast.success(res.message)
      } catch (error) {
        if (error instanceof HTTPError) {
          const res = await error.response.json<ApiErrorResponse>()
          toast.error(res.message)
        }
      }
    })
  }

  return (
    <form onSubmit={form.handleSubmit(onSubmit)}>
      <FieldGroup>
        <Controller
          control={form.control}
          name='fullname'
          render={({ field, fieldState }) => (
            <Field data-invalid={fieldState.invalid}>
              <FieldLabel htmlFor={field.name}>ФИО</FieldLabel>
              <InputGroup data-disabled={isPending}>
                <InputGroupInput
                  {...field}
                  aria-invalid={fieldState.invalid}
                  disabled={isPending}
                  id={field.name}
                  placeholder='Иванов Иван Иванович'
                  type='text'
                />
                <InputGroupAddon>
                  <IdCardIcon />
                </InputGroupAddon>
              </InputGroup>
              {fieldState.invalid && <FieldError errors={[fieldState.error]} />}
            </Field>
          )}
        />
        <Field orientation='responsive' className='justify-end'>
          <Button type='submit' disabled={isPending}>
            Сохранить
            {isPending ? <Spinner /> : <SaveIcon />}
          </Button>
        </Field>
      </FieldGroup>
    </form>
  )
}