'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useCreateProject, useUpdateProject } from '@/lib/hooks/use-projects';
import type { Project } from '@/types/project';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';

const projectSchema = z.object({
  name: z
    .string()
    .min(1, 'Name is required')
    .max(100, 'Name must be less than 100 characters'),
  key: z
    .string()
    .min(3, 'Key must be at least 3 characters')
    .max(10, 'Key must be less than 10 characters')
    .regex(/^[A-Z]+$/, 'Key must be uppercase letters only'),
  description: z
    .string()
    .max(500, 'Description must be less than 500 characters')
    .optional(),
});

type ProjectFormValues = z.infer<typeof projectSchema>;

interface ProjectFormProps {
  project?: Project;
  onSuccess?: () => void;
  onCancel?: () => void;
}

export function ProjectForm({ project, onSuccess, onCancel }: ProjectFormProps) {
  const isEditing = !!project;
  const createProject = useCreateProject();
  const updateProject = useUpdateProject(project?.id || '');

  const form = useForm<ProjectFormValues>({
    resolver: zodResolver(projectSchema),
    defaultValues: {
      name: project?.name || '',
      key: project?.key || '',
      description: project?.description || '',
    },
  });

  async function onSubmit(data: ProjectFormValues) {
    try {
      if (isEditing) {
        await updateProject.mutateAsync(data);
        toast.success('Project updated successfully');
      } else {
        await createProject.mutateAsync(data);
        toast.success('Project created successfully');
      }
      onSuccess?.();
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Operation failed';
      toast.error(message);
    }
  }

  const isLoading = createProject.isPending || updateProject.isPending;

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Project Name *</FormLabel>
              <FormControl>
                <Input placeholder="e.g., ColaFlow" {...field} />
              </FormControl>
              <FormDescription>
                The display name for your project
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="key"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Project Key *</FormLabel>
              <FormControl>
                <Input
                  placeholder="e.g., COLA"
                  {...field}
                  onChange={(e) => {
                    // Auto-uppercase
                    const value = e.target.value.toUpperCase();
                    field.onChange(value);
                  }}
                  maxLength={10}
                />
              </FormControl>
              <FormDescription>
                3-10 uppercase letters (used in issue IDs like COLA-123)
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Description</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="Brief description of the project..."
                  className="resize-none"
                  rows={4}
                  {...field}
                />
              </FormControl>
              <FormDescription>
                Optional description of your project (max 500 characters)
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="flex justify-end gap-3">
          {onCancel && (
            <Button
              type="button"
              variant="outline"
              onClick={onCancel}
              disabled={isLoading}
            >
              Cancel
            </Button>
          )}
          <Button type="submit" disabled={isLoading}>
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {isEditing ? 'Update Project' : 'Create Project'}
          </Button>
        </div>
      </form>
    </Form>
  );
}
