'use client';
import TechnologySelector from '@/components/builder/technologies/TechnologySelector';
import { Button } from '@/components/ui/button';
import { FileInput } from '@/components/ui/file-input';
import { Form, FormControl, FormField, FormItem, FormMessage } from '@/components/ui/form';
import { FormInput } from '@/components/ui/form-input';
import { Label } from '@/components/ui/label';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { Project, projectFormSchema, ProjectFormValues } from '@/src/types/project';
import { ProjectFormProps } from '@/types/project';
import { zodResolver } from '@hookform/resolvers/zod';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { cn } from '@/src/lib/utils';
import { VercelProjectSelector } from './VercelProjectSelector';
import { GetProjectsProjects } from '@vercel/sdk/models/getprojectsop.js';
import { getRepoUrl } from '@/utils/vercel';
import { useSession } from 'next-auth/react';

export function ProjectForm({
  project,
  onFieldUpdate,
  onSubmit,
  cancelAction,
  isEditor = false,
  isEdit = false,
  className,
}: ProjectFormProps) {
  const form = useForm<ProjectFormValues>({
    resolver: zodResolver(projectFormSchema),
    defaultValues: project,
  });
  const [technologies, setTechnologies] = useState<string[]>(project?.technologies || []);
  const [vercelProjectId, setVercelProjectId] = useState<string | undefined>(project?.vercelProjectId ?? undefined);
  const { data: session } = useSession();

  const handleFieldChange = (field: keyof ProjectFormValues, value: string) => {
    form.setValue(field, value);
    if (onFieldUpdate && field in (project || {})) {
      onFieldUpdate(field as keyof Project, value);
    }
  };

  const { handle, isLoading } = useApiWithToast();

  const handleImageUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    const data = await handle<{ publicUrl: string }>(
      fetch('/api/image', {
        method: 'POST',
        body: formData,
      })
    );

    if (data?.publicUrl) {
      form.setValue('image', data.publicUrl);
    }
  };

  const handleVercelProjectSelect = (vercelProject: GetProjectsProjects | null) => {
    form.setValue('vercelProjectId', vercelProject?.id);
    if (vercelProject) {
      setVercelProjectId(vercelProject.id);
      const latestDeployment = vercelProject.latestDeployments?.[0];
      const url = latestDeployment?.alias?.[0];
      const meta = latestDeployment?.meta;
      if (meta) {
        const repoUrl = getRepoUrl(meta) ?? '';
        handleFieldChange('gitUrl', repoUrl);
        form.setValue('gitUrl', repoUrl);
      }
    
      if (url) {
        handleFieldChange('url', 'https://' + url);
        form.setValue('url', 'https://' + url);
      }
    }
    else {
      setVercelProjectId(undefined);
      handleFieldChange('gitUrl', '');
      form.setValue('gitUrl', '');
      handleFieldChange('url', '');
      form.setValue('url', '');
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className={cn('space-y-4', className)} noValidate>
        <FormField
          control={form.control}
          name='title'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  label='Title'
                  {...field}
                  onChange={(e) => handleFieldChange('title', e.target.value)}
                  className='border-neutral-800'
                  required
                  value={field.value ?? ''}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name='description'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  label='Description'
                  {...field}
                  onChange={(e) => handleFieldChange('description', e.target.value)}
                  required
                  className='border-neutral-800'
                  value={field.value ?? ''}
                  isTextArea
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {isEditor ? (
          <FormField
            control={form.control}
            name='image'
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <FormInput
                    label='Image URL'
                    {...field}
                    onChange={(e) => handleFieldChange('image', e.target.value)}
                    required
                    className='border-neutral-800'
                    value={field.value ?? ''}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        ) : (
          <div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
            <div>
              <FileInput
                label='Project Image'
                name='image'
                accept='image/*'
                isLoading={isLoading}
                defaultValue={project?.image ?? ''}
                onFileSelect={async (file: File | null) => {
                  if (file) {
                    await handleImageUpload(file);
                  }
                }}
                required
                />
                {form.formState.errors.image && (
                  <p className="text-sm text-red-500 mt-1">
                    {form.formState.errors.image.message}
                  </p>
                )}
            </div>

            <div>
              <Label htmlFor='technologies'>Technologies</Label>
              <TechnologySelector
                onTechnologySelect={(tech) => {
                  if (tech && !technologies.includes(tech)) {
                    setTechnologies([...technologies, tech]);
                    handleFieldChange('technologies', JSON.stringify([...technologies, tech]));
                    form.setValue('technologies', [...technologies, tech]);
                  }
                }}
                selectedTechnologies={technologies}
                removeTechnology={(tech) => {
                  const newTechs = technologies.filter((t) => t !== tech);
                  handleFieldChange('technologies', JSON.stringify(newTechs));
                  setTechnologies(newTechs);
                  form.setValue('technologies', newTechs);
                }}
              />
            </div>
          </div>
        )}

        {isEditor && (
          <div className='text-neutral-800'>
            <Label htmlFor='technologies' className='text-neutral-800'>
              Technologies
            </Label>
            <TechnologySelector
              onTechnologySelect={(tech) => {
                if (tech && !technologies.includes(tech)) {
                  setTechnologies([...technologies, tech]);
                  handleFieldChange('technologies', JSON.stringify([...technologies, tech]));
                  form.setValue('technologies', [...technologies, tech]);
                }
              }}
              selectedTechnologies={technologies}
              removeTechnology={(tech) => {
                const newTechs = technologies.filter((t) => t !== tech);
                handleFieldChange('technologies', JSON.stringify(newTechs));
                setTechnologies(newTechs);
                form.setValue('technologies', newTechs);
              }}
            />
          </div>
        )}
        {process.env.NODE_ENV === 'production' && session?.user.vercelAccessToken && (
          <VercelProjectSelector
            onProjectSelect={handleVercelProjectSelect}
            selectedProjectId={vercelProjectId}
          />
        )}

        <FormField
          control={form.control}
          name='url'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  label='Project URL'
                  {...field}
                  onChange={(e) => handleFieldChange('url', e.target.value)}
                  placeholder='Project URL'
                  className='border-neutral-800'
                  value={field.value ?? ''}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name='gitUrl'
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <FormInput
                  label='Git URL'
                  {...field}
                  onChange={(e) => {
                    handleFieldChange('gitUrl', e.target.value);
                  }}
                  value={field.value ?? ''}
                  className='border-neutral-800'
                  placeholder='Git URL'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className='flex justify-end gap-2'>
          <Button type='button' variant='light-outline' onClick={cancelAction}>
            Cancel
          </Button>
          <Button type='submit' variant='default'>
            {isEdit ? 'Update Project' : isEditor ? 'Add to Portfolio' : 'Save Project'}
          </Button>
        </div>
      </form>
    </Form>
  );
}
