'use client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useAppForm } from '@/components/ui/tanstack-form';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useTransition } from 'react';
import { toast } from 'sonner';
import * as z from 'zod';

const formSchema = z.object({
  email: z.string().email({ message: 'Enter a valid email address' }),
  password: z.string().min(8, { message: 'Password must be at least 8 characters' })
});

export default function UserAuthForm() {
  const router = useRouter();
  const [loading, startTransition] = useTransition();

  const form = useAppForm({
    defaultValues: {
      email: 'demo@example.com',
      password: 'password123'
    },
    validators: {
      onSubmit: formSchema
    },
    onSubmit: ({ value }) => {
      startTransition(async () => {
        const result = await signIn('credentials', {
          email: value.email,
          password: value.password,
          redirect: false
        });

        if (result?.error) {
          toast.error('Invalid email or password');
          return;
        }

        toast.success('Signed in successfully');
        router.push('/dashboard/overview');
        router.refresh();
      });
    }
  });

  return (
    <>
      <form.AppForm>
        <form.Form className='w-full space-y-2'>
          <form.AppField
            name='email'
            children={(field) => (
              <field.FieldSet>
                <field.Field>
                  <field.FieldLabel htmlFor={field.name}>Email</field.FieldLabel>
                  <Input
                    id={field.name}
                    name={field.name}
                    value={field.state.value}
                    onBlur={field.handleBlur}
                    onChange={(e) => field.handleChange(e.target.value)}
                    placeholder='Enter your email...'
                    disabled={loading}
                    aria-invalid={field.state.meta.isTouched && !field.state.meta.isValid}
                  />
                </field.Field>
                <field.FieldError />
              </field.FieldSet>
            )}
          />
          <form.AppField
            name='password'
            children={(field) => (
              <field.FieldSet>
                <field.Field>
                  <field.FieldLabel htmlFor={field.name}>Password</field.FieldLabel>
                  <Input
                    id={field.name}
                    name={field.name}
                    type='password'
                    value={field.state.value}
                    onBlur={field.handleBlur}
                    onChange={(e) => field.handleChange(e.target.value)}
                    placeholder='Enter your password...'
                    disabled={loading}
                    aria-invalid={field.state.meta.isTouched && !field.state.meta.isValid}
                  />
                </field.Field>
                <field.FieldError />
              </field.FieldSet>
            )}
          />
          <Button disabled={loading} className='mt-2 ml-auto w-full' type='submit'>
            Continue with Email
          </Button>
        </form.Form>
      </form.AppForm>
    </>
  );
}
