'use client';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { AuthService } from '@/src/services/AuthService';
import { LoginFormData } from '@/src/types/auth';
import { loginSchema } from '@/types/auth';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { IoIosLock } from 'react-icons/io';
import { MdOutlineMail } from 'react-icons/md';
import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';

export default function LoginForm() {
  const { handle } = useApiWithToast();
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const [emailSent, setEmailSent] = useState(false);

  const form = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: { emailOrUsername: '', password: '' },
  });

  const forgotPasswordForm = useForm<{ email: string }>({
    defaultValues: { email: '' },
  });

  const onSubmit = async (values: LoginFormData) => {
    await handle(AuthService.login(values), {
      redirectTo: '/dashboard',
    });
  };

  const onForgotPassword = async (values: { email: string }) => {
    await handle(AuthService.forgotPassword(values.email), {
      messageOnSuccess: 'Password reset link has been sent to your email',
      messageOnError: 'Password reset link has been sent to your email',
    });
    setEmailSent(true);
  };

  return (
    <>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className='gap-2 flex flex-col max-w-[530px]'>
          <FormField
            control={form.control}
            name='emailOrUsername'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    placeholder='Email or Username'
                    {...field}
                    className='border-neutral-900 rounded-md !text-lg h-auto bg-white placeholder:text-neutral-500'
                    Icon={MdOutlineMail}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name='password'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    placeholder='Password'
                    type='password'
                    {...field}
                    className='border-neutral-900 rounded-md !text-lg h-auto bg-white placeholder:text-neutral-500'
                    Icon={IoIosLock}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <div className='flex justify-end'>
            <button
              type='button'
              onClick={() => setShowForgotPassword(true)}
              className='text-sm text-neutral-200 hover:text-neutral-400 underline'
            >
              Forgot password?
            </button>
          </div>
          <Button
            type='submit'
            className='hover:bg-neutral-900 border-neutral-900 border-2 rounded-md bg-white text-black hover:text-white'
          >
            Sign in
          </Button>
        </form>
      </Form>

      <Dialog open={showForgotPassword} onOpenChange={setShowForgotPassword}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className='text-neutral-700'>Reset your password</DialogTitle>
          </DialogHeader>
          {emailSent ? (
            <div className='space-y-4'>
              <p className='text-neutral-600'>
                We&apos;ve sent a password reset link to your email address. Please check your inbox and follow the
                instructions to reset your password.
              </p>
              <Button
                onClick={() => {
                  setShowForgotPassword(false);
                  setEmailSent(false);
                }}
                className='w-full'
                variant='default'
              >
                Close
              </Button>
            </div>
          ) : (
            <Form {...forgotPasswordForm}>
              <form onSubmit={forgotPasswordForm.handleSubmit(onForgotPassword)} className='space-y-4'>
                <FormField
                  control={forgotPasswordForm.control}
                  name='email'
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input
                          placeholder='Enter your email'
                          {...field}
                          className='border-neutral-900 rounded-md !text-lg h-auto bg-white placeholder:text-neutral-500'
                          Icon={MdOutlineMail}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <Button type='submit' className='w-full' variant='default'>
                  Send reset link
                </Button>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}
