'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';

import { useLazyLoginQuery } from '@/entities/auth';

import { SubmitButton } from '@/shared/components/submit-button';
import { useTextController } from '@/shared/language/hooks/use-text-controller';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/shared/shadcn-ui/form';
import { Input } from '@/shared/shadcn-ui/input';

import {
  LoginFormData,
  loginFormSchema,
} from '../../../../entities/auth/model/validation/login-form.schema';

interface LoginFormProps {
  type: 'bonus' | 'corporate';
}

export const LoginForm = ({ type }: LoginFormProps) => {
  const { t } = useTextController();

  const router = useRouter();
  const [login, { isLoading: isLoginLoading }] = useLazyLoginQuery();

  const form = useForm<LoginFormData>({
    resolver: zodResolver(loginFormSchema),
    defaultValues: {
      phoneNumber: '',
      cardNumber: '',
    },
  });

  const onSubmit = async (data: LoginFormData) => {
    await login({ ...data, type }).unwrap();

    toast.success('Logged in successfully!');
    router.push(
      type === 'bonus' ? '/customer-dashboard' : '/corporate-dashboard',
    );
  };

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className='mx-auto space-y-4'
      >
        <FormField
          control={form.control}
          name='phoneNumber'
          render={({ field }) => (
            <FormItem className='flex flex-col'>
              <FormLabel>{t('auth.phoneNumber')}</FormLabel>
              <FormControl>
                <Input
                  type='tel'
                  placeholder='+992 XXX XX XX XX'
                  {...field}
                  inputMode='tel'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name='cardNumber'
          render={({ field }) => (
            <FormItem className='flex flex-col'>
              <FormLabel>{t('auth.cardNumber')}</FormLabel>
              <FormControl>
                <Input
                  type='text'
                  placeholder='XXXX-XXXX-XXXX-XXXX'
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <SubmitButton
          isLoading={isLoginLoading}
          type='submit'
          className='w-full'
          disabled={isLoginLoading}
        />
      </form>
    </Form>
  );
};
