'use client';

import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Input,
} from '@/components/ui';
import Link from 'next/link';
import { signIn } from '@/lib/actions';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/components/context/auth';
import { useEffect, useState } from 'react';
import { StatusMessage, SubmitButton } from '@/components/default';
import { Separator } from '@/components/ui';
import { SignInWithMicrosoft } from '@/components/default/auth/SignInWithMicrosoft';
import { SignInWithApple } from '@/components/default/auth/SignInWithApple';

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

const Login = () => {
  const router = useRouter();
  const { isAuthenticated, isLoading, refreshUserData } = useAuth();
  const [statusMessage, setStatusMessage] = useState('');

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: '',
      password: '',
    },
  });

  // Redirect if already authenticated
  useEffect(() => {
    if (isAuthenticated) {
      router.push('/');
    }
  }, [isAuthenticated, router]);

  const handleSignIn = async (values: z.infer<typeof formSchema>) => {
    try {
      setStatusMessage('');
      const formData = new FormData();
      formData.append('email', values.email);
      formData.append('password', values.password);
      const result = await signIn(formData);
      if (result?.success) {
        await refreshUserData();
        form.reset();
        router.push('');
      } else {
        setStatusMessage(`Error: ${result.error}`);
      }
    } catch (error) {
      setStatusMessage(
        `Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`,
      );
    }
  };

  return (
    <Card className='min-w-xs md:min-w-sm'>
      <CardHeader>
        <CardTitle className='text-3xl font-medium'>Sign In</CardTitle>
        <CardDescription className='text-foreground'>
          Don&apos;t have an account?{' '}
          <Link className='font-medium underline' href='/sign-up'>
            Sign up
          </Link>
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(handleSignIn)}
            className='flex flex-col min-w-64 space-y-6 pb-4'
          >
            <FormField
              control={form.control}
              name='email'
              render={({ field }) => (
                <FormItem>
                  <FormLabel className='text-lg'>Email</FormLabel>
                  <FormControl>
                    <Input
                      type='email'
                      placeholder='you@example.com'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name='password'
              render={({ field }) => (
                <FormItem>
                  <div className='flex justify-between'>
                    <FormLabel className='text-lg'>Password</FormLabel>
                    <Link
                      className='text-xs text-foreground underline text-right'
                      href='/forgot-password'
                    >
                      Forgot Password?
                    </Link>
                  </div>
                  <FormControl>
                    <Input
                      type='password'
                      placeholder='Your password'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {statusMessage &&
              (statusMessage.includes('Error') ||
              statusMessage.includes('error') ||
              statusMessage.includes('failed') ||
              statusMessage.includes('invalid') ? (
                <StatusMessage message={{ error: statusMessage }} />
              ) : (
                <StatusMessage message={{ message: statusMessage }} />
              ))}
            <SubmitButton
              disabled={isLoading}
              pendingText='Signing In...'
              className='text-[1.0rem] cursor-pointer'
            >
              Sign in
            </SubmitButton>
          </form>
        </Form>

        <div className='flex items-center w-full gap-4'>
          <Separator className='flex-1 bg-accent py-0.5' />
          <span className='text-sm text-muted-foreground'>or</span>
          <Separator className='flex-1 bg-accent py-0.5' />
        </div>
        <SignInWithMicrosoft />
        <SignInWithApple />
      </CardContent>
    </Card>
  );
};

export default Login;
