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

const schema = z.object({
  userName: z
    .string()
    .min(3)
    .max(32)
    .regex(/^[a-zA-Z0-9_.-]+$/),
  password: z.string().min(8),
})

type FormValues = z.infer<typeof schema>

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

  const onSubmit = async (values: FormValues) => {
    try {
      await registerUser(values.userName, values.password)
      const auth = await login(values.userName, values.password)
      applyAuthResponse(auth)
      onSuccess()
    } catch (error) {
      const message =
        error instanceof HttpError && error.status === 409 ? t('auth.duplicateUserName') : t('auth.genericError')
      toast.error(message)
    }
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
      <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-sm text-red-500">{t('auth.userNameHint')}</p>
        ) : (
          <p className="text-xs text-muted-foreground">{t('auth.userNameHint')}</p>
        )}
      </div>
      <div className="flex flex-col gap-1.5">
        <Label htmlFor="password">{t('auth.password')}</Label>
        <Input id="password" type="password" autoComplete="new-password" {...registerField('password')} />
        {errors.password ? (
          <p className="text-sm text-red-500">{t('auth.passwordHint')}</p>
        ) : (
          <p className="text-xs text-muted-foreground">{t('auth.passwordHint')}</p>
        )}
      </div>
      <Button type="submit" disabled={isSubmitting}>
        {t('auth.submitRegister')}
      </Button>
    </form>
  )
}
