'use client';
import { createFrameworkIcons } from '@/components/icons/FrameworkIcons';
import { Button } from '@/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormMessage } from '@/components/ui/form';
import { FormInput } from '@/components/ui/form-input';
import { FormKeyValueRepeater } from '@/components/ui/form-key-value-repeater';
import { FormSearchableSelect } from '@/components/ui/form-searchable-select';
import { useVercelRepositories } from '@/src/services/VercelService';
import { DeploymentFormProps, deploymentFormSchema, type DeploymentFormValues } from '@/types/deployment';
import { zodResolver } from '@hookform/resolvers/zod';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { FaRocket } from 'react-icons/fa';

export function DeploymentForm({
  onSubmit,
  isDeploying,
  isDisabled,
  isEdit = false,
  defaultValues = {},
}: DeploymentFormProps) {
  const [search, setSearch] = useState('');
  const { repositories, isLoading } = useVercelRepositories(search);

  const form = useForm<DeploymentFormValues>({
    resolver: zodResolver(deploymentFormSchema),
    defaultValues,
  });

  const { formState } = form;
  const handleSubmit = async (values: DeploymentFormValues) => {
    try {
      const valuesToSubmit: Partial<DeploymentFormValues> = { ...values };
      if (!formState.dirtyFields['name']) {
        delete valuesToSubmit.name;
      }
      await onSubmit(valuesToSubmit);
    } catch (error) {
      console.error('Form submission error:', error);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-4 text-neutral-200' noValidate>
        {!isEdit && (
          <FormSearchableSelect
            name='gitRepository'
            label='Repository'
            loading={isLoading}
            options={repositories?.map((repo) => ({
              label: (
                <div className='flex flex-row gap-2 items-center'>
                  <span>{repo.name}</span>
                </div>
              ),
              value: {
                repo: `${repo.namespace}/${repo.slug}`,
                type: repo.provider,
                id: repo.id,
                ref: repo.defaultBranch,
              },
            }))}
            onSearch={setSearch}
            placeholder='Search for a repository...'
            error={form.formState.errors.gitRepository?.message}
            shouldFilter={false}
            required
            defaultValue={defaultValues.gitRepository?.repo}
          />
        )}

        <FormField
          control={form.control}
          name='name'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  {...field}
                  name='name'
                  label='Project Name'
                  placeholder='Project name'
                  className='rounded-sm'
                  required
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormSearchableSelect
          name='framework'
          label="Framework (if you don't select one, Vercel will auto-detect it)"
          defaultValue={defaultValues.framework ?? undefined}
          options={Object.entries(createFrameworkIcons('h-[15px] w-auto')).map(([key, value]) => ({
            label: (
              <div className='flex flex-row gap-2 items-center'>
                {value} {key}
              </div>
            ),
            value: key,
          }))}
        />

        <FormKeyValueRepeater
          name='env'
          label='Environment Variables'
          keyPlaceholder='ENVIRONMENT_KEY'
          valuePlaceholder='ENVIRONMENT_VALUE'
          isSecret={true}
          defaultValue={defaultValues.env}
        />

        <FormField
          control={form.control}
          name='rootDirectory'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  {...field}
                  label='Root Directory'
                  placeholder='./'
                  className='rounded-sm'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name='buildCommand'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  {...field}
                  label='Build Command'
                  placeholder='npm run build'
                  className='rounded-sm'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name='outputDirectory'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  {...field}
                  label='Output Directory'
                  placeholder='build'
                  className='rounded-sm'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name='installCommand'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  {...field}
                  label='Install Command'
                  placeholder='npm install'
                  className='rounded-sm'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button
          type='submit'
          variant='light-outline'
          className='w-full'
          disabled={isDeploying || isDisabled || !formState.isDirty}
        >
          {isEdit ? 'Update Configuration' : 'Deploy'} {!isEdit && <FaRocket className='ml-2' />}
        </Button>
      </form>
    </Form>
  );
}
