import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { toast } from '@/shared/ui/toast-store'
import { HttpError } from '@/shared/api/client'
import { applyAuthResponse, login } from './api'

const schema = z.object({
  userName: z.string().min(1),
  password: z.string().min(1),
})

type FormValues = z.infer<typeof schema>

export function LoginForm({ onSuccess }: { onSuccess: () => void }) {
  const { t } = useTranslation()
  const {
    register: registerField,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<FormValues>({ resolver: zodResolver(schema) })

  const onSubmit = async (values: FormValues) => {
    try {
      const auth = await login(values.userName, values.password)
      applyAuthResponse(auth)
      onSuccess()
    } catch (error) {
      const status = error instanceof HttpError ? error.status : 0
      let message = t('auth.genericError')
      if (status === 401) message = t('auth.invalidCredentials')
      else if (status === 403) message = t('auth.blocked')
      toast.error(message)
    }
  }

  return (
    <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
      <div className="flex flex-col gap-1.5">
        <Label htmlFor="userName">{t('auth.userName')}</Label>
        <Input id="userName" autoComplete="username" {...registerField('userName')} />
        {errors.userName && <p className="text-xs text-red-500">{errors.userName.message}</p>}
      </div>
      <div className="flex flex-col gap-1.5">
        <Label htmlFor="password">{t('auth.password')}</Label>
        <Input id="password" type="password" autoComplete="current-password" {...registerField('password')} />
        {errors.password && <p className="text-xs text-red-500">{errors.password.message}</p>}
      </div>
      <Button type="submit" disabled={isSubmitting}>
        {t('auth.submitLogin')}
      </Button>
    </form>
  )
}
