'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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useCreateEpic, useUpdateEpic } from '@/lib/hooks/use-epics';
import type { Epic, WorkItemPriority } from '@/types/project';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';

const epicSchema = z.object({
  projectId: z.string().min(1, 'Project is required'),
  title: z
    .string()
    .min(1, 'Title is required')
    .max(200, 'Title must be less than 200 characters'),
  description: z
    .string()
    .max(2000, 'Description must be less than 2000 characters')
    .optional(),
  priority: z.enum(['Low', 'Medium', 'High', 'Critical']),
  estimatedHours: z
    .number()
    .min(0, 'Estimated hours must be positive')
    .optional()
    .or(z.literal('')),
});

type EpicFormValues = z.infer<typeof epicSchema>;

interface EpicFormProps {
  epic?: Epic;
  projectId?: string;
  onSuccess?: () => void;
  onCancel?: () => void;
}

export function EpicForm({ epic, projectId, onSuccess, onCancel }: EpicFormProps) {
  const isEditing = !!epic;
  const createEpic = useCreateEpic();
  const updateEpic = useUpdateEpic();

  const form = useForm<EpicFormValues>({
    resolver: zodResolver(epicSchema),
    defaultValues: {
      projectId: epic?.projectId || projectId || '',
      title: epic?.title || '',
      description: epic?.description || '',
      priority: epic?.priority || 'Medium',
      estimatedHours: epic?.estimatedHours || ('' as any),
    },
  });

  async function onSubmit(data: EpicFormValues) {
    try {
      if (isEditing && epic) {
        await updateEpic.mutateAsync({
          id: epic.id,
          data: {
            title: data.title,
            description: data.description,
            priority: data.priority,
            estimatedHours:
              typeof data.estimatedHours === 'number' ? data.estimatedHours : undefined,
          },
        });
        toast.success('Epic updated successfully');
      } else {
        await createEpic.mutateAsync({
          projectId: data.projectId,
          title: data.title,
          description: data.description,
          priority: data.priority,
          estimatedHours:
            typeof data.estimatedHours === 'number' ? data.estimatedHours : undefined,
        });
        toast.success('Epic created successfully');
      }
      onSuccess?.();
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Operation failed';
      toast.error(message);
    }
  }

  const isLoading = createEpic.isPending || updateEpic.isPending;

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="title"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Epic Title *</FormLabel>
              <FormControl>
                <Input placeholder="e.g., User Authentication System" {...field} />
              </FormControl>
              <FormDescription>A clear, concise title for this epic</FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Description</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="Detailed description of the epic..."
                  className="resize-none"
                  rows={6}
                  {...field}
                />
              </FormControl>
              <FormDescription>
                Optional detailed description (max 2000 characters)
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="grid grid-cols-2 gap-4">
          <FormField
            control={form.control}
            name="priority"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Priority *</FormLabel>
                <Select onValueChange={field.onChange} defaultValue={field.value}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Select priority" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="Low">Low</SelectItem>
                    <SelectItem value="Medium">Medium</SelectItem>
                    <SelectItem value="High">High</SelectItem>
                    <SelectItem value="Critical">Critical</SelectItem>
                  </SelectContent>
                </Select>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="estimatedHours"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Estimated Hours</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    placeholder="e.g., 40"
                    min="0"
                    step="0.5"
                    {...field}
                    onChange={(e) => {
                      const value = e.target.value;
                      field.onChange(value === '' ? '' : parseFloat(value));
                    }}
                    value={field.value === undefined ? '' : field.value}
                  />
                </FormControl>
                <FormDescription>Optional time estimate</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <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 Epic' : 'Create Epic'}
          </Button>
        </div>
      </form>
    </Form>
  );
}
