"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 { useCreateStory, useUpdateStory } from "@/lib/hooks/use-stories";
import { useEpics } from "@/lib/hooks/use-epics";
import type { Story } from "@/types/project";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";
import { useAuthStore } from "@/stores/authStore";
import { AcceptanceCriteriaEditor } from "./acceptance-criteria-editor";
import { TagsInput } from "./tags-input";

const storySchema = z.object({
  epicId: z.string().min(1, "Parent Epic 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("")),
  // Sprint 4 Story 3: New fields
  acceptanceCriteria: z.array(z.string()).optional(),
  assigneeId: z.string().optional(),
  tags: z.array(z.string()).optional(),
  storyPoints: z
    .number()
    .min(0, "Story points must be positive")
    .max(100, "Story points must be less than 100")
    .optional()
    .or(z.literal("")),
});

type StoryFormValues = z.infer<typeof storySchema>;

interface StoryFormProps {
  story?: Story;
  epicId?: string;
  projectId?: string;
  onSuccess?: () => void;
  onCancel?: () => void;
}

export function StoryForm({ story, epicId, projectId, onSuccess, onCancel }: StoryFormProps) {
  const isEditing = !!story;
  const user = useAuthStore((state) => state.user);
  const createStory = useCreateStory();
  const updateStory = useUpdateStory();

  // Fetch epics for parent epic selection
  const { data: epics = [], isLoading: epicsLoading } = useEpics(projectId);

  const form = useForm<StoryFormValues>({
    resolver: zodResolver(storySchema),
    defaultValues: {
      epicId: story?.epicId || epicId || "",
      title: story?.title || "",
      description: story?.description || "",
      priority: story?.priority || "Medium",
      estimatedHours: story?.estimatedHours || ("" as const),
      // Sprint 4 Story 3: New field defaults
      acceptanceCriteria: story?.acceptanceCriteria || [],
      assigneeId: story?.assigneeId || "",
      tags: story?.tags || [],
      storyPoints: story?.storyPoints || ("" as const),
    },
  });

  async function onSubmit(data: StoryFormValues) {
    try {
      if (isEditing && story) {
        await updateStory.mutateAsync({
          id: story.id,
          data: {
            title: data.title,
            description: data.description,
            priority: data.priority,
            estimatedHours:
              typeof data.estimatedHours === "number" ? data.estimatedHours : undefined,
            // Sprint 4 Story 3: New fields
            acceptanceCriteria: data.acceptanceCriteria,
            assigneeId: data.assigneeId || undefined,
            tags: data.tags,
            storyPoints: typeof data.storyPoints === "number" ? data.storyPoints : undefined,
          },
        });
        toast.success("Story updated successfully");
      } else {
        if (!user?.id) {
          toast.error("User not authenticated");
          return;
        }
        if (!projectId) {
          toast.error("Project ID is required");
          return;
        }
        await createStory.mutateAsync({
          epicId: data.epicId,
          projectId,
          title: data.title,
          description: data.description,
          priority: data.priority,
          estimatedHours: typeof data.estimatedHours === "number" ? data.estimatedHours : undefined,
          createdBy: user.id,
          // Sprint 4 Story 3: New fields
          acceptanceCriteria: data.acceptanceCriteria,
          assigneeId: data.assigneeId || undefined,
          tags: data.tags,
          storyPoints: typeof data.storyPoints === "number" ? data.storyPoints : undefined,
        });
        toast.success("Story created successfully");
      }
      onSuccess?.();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Operation failed";
      toast.error(message);
    }
  }

  const isLoading = createStory.isPending || updateStory.isPending;

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="epicId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Parent Epic *</FormLabel>
              <Select
                onValueChange={field.onChange}
                defaultValue={field.value}
                disabled={isEditing || !!epicId}
              >
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select parent epic" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {epicsLoading ? (
                    <div className="text-muted-foreground p-2 text-sm">Loading epics...</div>
                  ) : epics.length === 0 ? (
                    <div className="text-muted-foreground p-2 text-sm">No epics available</div>
                  ) : (
                    epics.map((epic) => (
                      <SelectItem key={epic.id} value={epic.id}>
                        {epic.name}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
              <FormDescription>
                {isEditing ? "Parent epic cannot be changed" : "Select the parent epic"}
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="title"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Story Title *</FormLabel>
              <FormControl>
                <Input placeholder="e.g., Login page with OAuth support" {...field} />
              </FormControl>
              <FormDescription>A clear, concise title for this story</FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Description</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="Detailed description of the story..."
                  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., 8"
                    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>

        {/* Sprint 4 Story 3: Acceptance Criteria */}
        <FormField
          control={form.control}
          name="acceptanceCriteria"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Acceptance Criteria</FormLabel>
              <FormControl>
                <AcceptanceCriteriaEditor
                  criteria={field.value || []}
                  onChange={field.onChange}
                  disabled={isLoading}
                />
              </FormControl>
              <FormDescription>
                Define conditions that must be met for this story to be complete
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Sprint 4 Story 3: Assignee and Story Points */}
        <div className="grid grid-cols-2 gap-4">
          <FormField
            control={form.control}
            name="assigneeId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Assignee</FormLabel>
                <Select onValueChange={field.onChange} value={field.value} disabled={isLoading}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Unassigned" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="">Unassigned</SelectItem>
                    {user?.id && <SelectItem value={user.id}>{user.fullName || "Me"}</SelectItem>}
                  </SelectContent>
                </Select>
                <FormDescription>Assign to team member</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="storyPoints"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Story Points</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    placeholder="e.g., 5"
                    min="0"
                    max="100"
                    step="1"
                    {...field}
                    onChange={(e) => {
                      const value = e.target.value;
                      field.onChange(value === "" ? "" : parseInt(value));
                    }}
                    value={field.value === undefined ? "" : field.value}
                    disabled={isLoading}
                  />
                </FormControl>
                <FormDescription>Fibonacci: 1, 2, 3, 5, 8, 13...</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* Sprint 4 Story 3: Tags */}
        <FormField
          control={form.control}
          name="tags"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Tags</FormLabel>
              <FormControl>
                <TagsInput
                  tags={field.value || []}
                  onChange={field.onChange}
                  disabled={isLoading}
                  placeholder="Add tags (press Enter)..."
                />
              </FormControl>
              <FormDescription>
                Add tags to categorize this story (e.g., frontend, bug, urgent)
              </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 Story" : "Create Story"}
          </Button>
        </div>
      </form>
    </Form>
  );
}
