'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 { forgotPassword } from '@/lib/queries';
import { useAuth } from '@/lib/hooks/context';
import { useEffect, useState, type ComponentProps } from 'react';
import { useRouter } from 'next/navigation';
import { useSupabaseClient } from '@/utils/supabase';
import { StatusMessage, SubmitButton } from '@/components/default/forms';
import { cn } from '@/lib/utils';

const forgotPasswordFormSchema = z.object({
  email: z.string().email({
    message: 'Please enter a valid email address.'
  }),
});

type ForgotPasswordCardProps = {
  cardClassName?: ComponentProps<typeof Card>['className'];
  cardProps?: Omit<ComponentProps<typeof Card>, 'className'>;
  cardTitleClassName?: ComponentProps<typeof CardTitle>['className'];
  cardTitleProps?: Omit<ComponentProps<typeof CardTitle>, 'className'>;
  cardDescriptionClassName?: ComponentProps<typeof CardDescription>['className'];
  cardDescriptionProps?: Omit<ComponentProps<typeof CardDescription>, 'className'>;
  signUpLinkClassName?: ComponentProps<typeof Link>['className'];
  signUpLinkProps?: Omit<ComponentProps<typeof Link>, 'className' | 'href'>;
  formClassName?: ComponentProps<'form'>['className'];
  formProps?: Omit<ComponentProps<'form'>, 'className' | 'onSubmit'>;
  formLabelClassName?: ComponentProps<typeof FormLabel>['className'];
  formLabelProps?: Omit<ComponentProps<typeof FormLabel>, 'className'>;
  buttonProps?: ComponentProps<typeof SubmitButton>;
};

export const ForgotPasswordCard = ({
  cardClassName,
  cardProps,
  cardTitleClassName,
  cardTitleProps,
  cardDescriptionClassName,
  cardDescriptionProps,
  signUpLinkClassName,
  signUpLinkProps,
  formClassName,
  formProps,
  formLabelClassName,
  formLabelProps,
  buttonProps = {
    pendingText: 'Sending Reset Link...',
  },
}: ForgotPasswordCardProps) => {
  const router = useRouter();
  const { isAuthenticated, loading, refreshUser } = useAuth();
  const [statusMessage, setStatusMessage] = useState('');
  const supabase = useSupabaseClient();

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

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

  const handleForgotPassword = async (values: z.infer<typeof forgotPasswordFormSchema>) => {
    try {
      setStatusMessage('');
      const formData = new FormData();
      formData.append('email', values.email);
      if (!supabase) throw new Error('Supabase client not found');
      const result = await forgotPassword(supabase, formData);
      if (result.error) throw new Error(result.error.message);
      await refreshUser();
      setStatusMessage('Check your email for a link to reset your password.');
      form.reset();
      router.push('');
    } catch (error) {
      setStatusMessage(
        `Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`,
      );
    }
  };

  return (
    <Card
      className={cn('min-w-xs sm:min-w-sm bg-card/50', cardClassName)}
      {...cardProps}
    >
      <CardHeader>
        <CardTitle
          className={cn('text-2xl font-medium', cardTitleClassName)}
          {...cardTitleProps}
        >
          Forgot Password
        </CardTitle>
        <CardDescription
          className={cn('text-sm text-foreground', cardDescriptionClassName)}
          {...cardDescriptionProps}
        >
          Don&apos;t have an account?{' '}
          <Link
            className={cn('font-medium underline', signUpLinkClassName)}
            href='/sign-up'
            {...signUpLinkProps}
          >
            Sign up!
          </Link>
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(handleForgotPassword)}
            className={cn('flex flex-col min-w-64 space-y-6', formClassName)}
            {...formProps}
          >
            <FormField
              control={form.control}
              name='email'
              render={({ field }) => (
                <FormItem>
                  <FormLabel
                    className={cn('text-xl', formLabelClassName)}
                    {...formLabelProps}
                  >
                    Email
                  </FormLabel>
                  <FormControl>
                    <Input
                      type='email'
                      placeholder='you@example.com'
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <SubmitButton
              disabled={loading}
              {...buttonProps}
            >
              Reset Password
            </SubmitButton>
            {statusMessage &&
              (statusMessage.includes('Error') ||
              statusMessage.includes('error') ||
              statusMessage.includes('failed') ||
              statusMessage.includes('invalid') ? (
                <StatusMessage message={{ error: statusMessage }} />
              ) : (
                <StatusMessage message={{ success: statusMessage }} />
              ))}
          </form>
        </Form>
      </CardContent>
    </Card>
  );
};
