'use client';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { FormInput } from '@/components/ui/form-input';
import { useUsers } from '@/src/services/UserService';
import { PortfolioContributor, PortfolioFormProps, portfolioFormSchema, type PortfolioFormValues } from '@/types/portfolio';
import { zodResolver } from '@hookform/resolvers/zod';
import { PortfolioContributorStatus, User } from '@prisma/client';
import { ChevronRight, PlusCircle, Trash2, Users } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { SearchableSelect } from '../ui/searchable-select';

export function PortfolioForm({ onSubmit, isLoading, defaultValues = {}, isEdit = false }: PortfolioFormProps) {
  const router = useRouter();
  const [contributors, setContributors] = useState<PortfolioContributor[]>(defaultValues.contributors ?? []);
  const [showContributors, setShowContributors] = useState(contributors.length > 0);
  const [newContributor, setNewContributor] = useState<PortfolioContributor | null>(null);
  const [shouldNavigateToEditor, setShouldNavigateToEditor] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const { users } = useUsers();

  const form = useForm<PortfolioFormValues>({
    resolver: zodResolver(portfolioFormSchema),
    defaultValues: { title: defaultValues.title },
    mode: 'onSubmit',
  });

  const handleSubmit = async (values: PortfolioFormValues) => {
    const formValues = {
      ...values,
      contributors,
    };
    await onSubmit(formValues, shouldNavigateToEditor);
  };

  const isEmailAlreadyAdded = (email: string) => {
    return contributors.some((c) => c.email.toLowerCase() === email.toLowerCase());
  };

  const addContributor = () => {
    if (newContributor && !isEmailAlreadyAdded(newContributor.email)) {
      setContributors([...contributors, newContributor]);
      setNewContributor(null);
    }
  };

  const addInviteEmail = () => {
    if (inviteEmail && !isEmailAlreadyAdded(inviteEmail)) {
      setContributors([...contributors, { id: '', email: inviteEmail, status: PortfolioContributorStatus.PENDING }]);
      setInviteEmail('');
    }
  };

  const removeContributor = (contributor: PortfolioContributor) => {
    setContributors(contributors.filter((c) => c.email !== contributor.email));
  };

  const availableUsers = users.filter(
    (user: User) => !contributors.some((c) => c.id === user.id)
  );

  if (isLoading) {
    return (
      <div className='animate-pulse space-y-4 p-6'>
        <div className='h-8 bg-neutral-700 rounded w-1/4'></div>
        <div className='h-[600px] bg-neutral-800 rounded'></div>
      </div>
    );
  }

  return (
    <Form {...form}>
      <form
        className='flex flex-col h-full space-y-6 mx-auto'
        onSubmit={form.handleSubmit(handleSubmit)}
        noValidate
      >
        <div className='space-y-6'>
          <FormField
            control={form.control}
            name='title'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <FormInput
                    {...field}
                    label='Portfolio Name'
                    placeholder='Enter portfolio name'
                    name='title'
                    required
                    className='text-lg'
                    value={field.value ?? ''}
                  />
                </FormControl>
                <FormDescription className='text-neutral-400'>
                  Choose a descriptive name for your portfolio
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {!showContributors ? (
            <div className='flex justify-start mt-8'>
              <Button
                type='button'
                variant='light-outline'
                className='flex items-center gap-2 border-dashed border-neutral-600'
                onClick={() => setShowContributors(true)}
              >
                <Users className='h-4 w-4' />
                Invite Contributors
                <ChevronRight className='h-4 w-4' />
              </Button>
            </div>
          ) : (
            <div className='space-y-6 border-t border-neutral-700 pt-6 mt-6'>
              <div className='flex items-center gap-2'>
                <Users className='h-5 w-5 text-neutral-400' />
                <h3 className='text-lg font-medium text-white'>Contributors</h3>
              </div>

              <div className='space-y-2'>
                <p className='text-sm text-neutral-300'>
                  Invite people to collaborate on this portfolio. Contributors can add their projects.
                </p>

                <div className='flex items-end gap-2'>
                  <div className='flex-1'>
                    <FormLabel htmlFor='contributor-email'>Search Existing Users</FormLabel>
                    <SearchableSelect
                      placeholder='Search for a user'
                      options={availableUsers.map((user: User) => ({
                        label: user.email,
                        value: { id: user.id, email: user.email, status: PortfolioContributorStatus.PENDING },
                      }))}
                      value={newContributor ?? undefined}
                      onChange={(contributor) => setNewContributor(contributor as PortfolioContributor)}
                      className='bg-neutral-800 border-neutral-700'
                    />
                  </div>
                  <Button
                    type='button'
                    onClick={addContributor}
                    disabled={!newContributor || isEmailAlreadyAdded(newContributor.email)}
                    className='flex items-center gap-1'
                  >
                    <PlusCircle className='w-4 h-4' /> Add
                  </Button>
                </div>

                <div className='mt-6 pt-6 border-t border-neutral-700'>
                  <h4 className='text-md font-medium text-white mb-4'>Invite New Users</h4>
                  <div className='flex items-end gap-2'>
                    <div className='flex-1'>
                      <FormInput
                        name='invite-email'
                        label='Email Address'
                        placeholder='Enter email address'
                        value={inviteEmail}
                        onChange={(e) => setInviteEmail(e.target.value)}
                      />
                    </div>
                    <Button
                      type='button'
                      onClick={addInviteEmail}
                      disabled={!inviteEmail || isEmailAlreadyAdded(inviteEmail)}
                      className='flex items-center gap-1'
                    >
                      <PlusCircle className='w-4 h-4' /> Add
                    </Button>
                  </div>
                </div>
              </div>

              <div className='space-y-2'>
                <FormLabel>Current Contributors</FormLabel>
                {contributors.length === 0 ? (
                  <div className='p-4 border border-dashed border-neutral-700 rounded-md text-center text-neutral-400'>
                    No contributors added yet
                  </div>
                ) : (
                    <div className='space-y-2 pr-2 max-h-[200px] overflow-y-auto'>
                      {contributors.map((contributor) => (
                        <div
                          key={crypto.randomUUID()}
                          className='flex items-center justify-between p-2 bg-neutral-200 rounded-md text-neutral-800'
                        >
                          <div className='flex items-center gap-3'>
                            <div>
                              <p className='text-sm font-medium'>{contributor.email}</p>
                              {(!contributor.id || (contributor.id && contributor.status == 'PENDING')) && (
                                <span className='text-xs text-neutral-500'>Pending invitation</span>
                              )}
                            </div>
                          </div>
                          <Button
                            type='button'
                            variant='ghost'
                            size='icon'
                            onClick={() => removeContributor(contributor)}
                          >
                            <Trash2 className='h-4 w-4 text-neutral-900' />
                          </Button>
                        </div>
                      ))}
                    </div>
                )}
              </div>
            </div>
          )}
        </div>

        <div className='flex flex-row justify-between sm:items-end pt-6 border-t border-neutral-700 h-full'>
          <Button type='button' variant='light-outline' onClick={() => router.back()}>
            Cancel
          </Button>

          <div className='flex gap-3 sm:flex-row flex-col w-fit items-end'>
            {isEdit ? (
              <Button type='submit' className='px-8'>
                Save Changes
              </Button>
            ) : (
              <>
                <Button
                  type='submit'
                  variant='light-outline'
                  onClick={() => setShouldNavigateToEditor(false)}
                  className='w-fit'
                >
                  Create
                </Button>
                <Button
                  type='submit'
                  onClick={() => setShouldNavigateToEditor(true)}
                >
                  Create & Continue to Editor
                </Button>
              </>
            )}
          </div>
        </div>
      </form>
    </Form>
  );
}
