'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 { registerSchema } from '@/types/auth';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { FaUserLarge } from 'react-icons/fa6';
import { IoIosLock } from 'react-icons/io';
import { MdOutlineMail } from 'react-icons/md';
import { z } from 'zod';
import { useSearchParams } from 'next/navigation';

interface RegisterFormProps {
  isInvitation?: boolean;
  invitationData?: {
    token: string;
    email: string;
    portfolioId: string;
    portfolioTitle: string;
  };
}

export default function RegisterForm({ isInvitation, invitationData }: RegisterFormProps) {
  const { handle } = useApiWithToast();
  const searchParams = useSearchParams();
  const invite = searchParams.get('invite');
  
  const form = useForm<z.infer<typeof registerSchema>>({
    resolver: zodResolver(registerSchema),
    defaultValues: { 
      email: invitationData?.email ?? '', 
      password: '', 
      username: '' 
    },
  });

  async function handleRegularSubmit(values: z.infer<typeof registerSchema>) {
    await handle(AuthService.register(values, invite), {
      redirectTo: '/dashboard',
    });
  }

  async function handleInvitationSubmit(values: z.infer<typeof registerSchema>) {
    if (!invitationData) return;
    
    await handle(
      AuthService.registerWithInvitation({
        ...values,
        token: invitationData.token,
        portfolioId: invitationData.portfolioId
      }),
      {
        redirectTo: '/dashboard',
      }
    );
  }

  return (
    <Form {...form}>
      <form 
        className='gap-2 flex flex-col max-w-[530px]' 
        onSubmit={form.handleSubmit(isInvitation ? handleInvitationSubmit : handleRegularSubmit)}
      >
        <FormField
          control={form.control}
          name='username'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  placeholder='Username'
                  {...field}
                  className='border-neutral-900 rounded-md !text-lg h-auto bg-white placeholder:text-neutral-500'
                  Icon={FaUserLarge}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name='email'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  placeholder='Email'
                  {...field}
                  className='border-neutral-900 rounded-md !text-lg h-auto bg-white placeholder:text-neutral-500'
                  Icon={MdOutlineMail}
                  disabled={isInvitation}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name='password'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <Input
                  placeholder='Password'
                  {...field}
                  className='border-neutral-900 rounded-md !text-lg h-auto bg-white placeholder:text-neutral-500'
                  type='password'
                  Icon={IoIosLock}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button
          type='submit'
          className='hover:bg-neutral-900 border-neutral-900 border-2 rounded-md bg-white text-black hover:text-white'
        >
          {isInvitation ? 'Sign Up and Collaborate' : 'Sign Up'}
        </Button>
      </form>
    </Form>
  );
}
