"use client";

import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Trash } from "lucide-react";

import { cn } from "@/lib/utils";
import { DatePicker } from "@/components/date-picker";
import { DottedSeparator } from "@/components/dotted-separator";
import { MemberAvatar } from "@/features/members/components/member-avatar";
import { ProjectAvatar } from "@/features/projects/components/project-avatar";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";
import { useConfirm } from "@/hooks/use-confirm";

import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { TagsInput } from "@/components/ui/tags-input";
import { Textarea } from "@/components/ui/textarea";

import { Epic } from "../types";
import { updateEpicSchema } from "../schemas";
import { useUpdateEpic } from "../api/use-update-epic";
import { useDeleteEpic } from "../api/use-delete-epic";
import { MemberRole } from "@/features/members/types";

interface EditEpicFormProps {
  onCancel?: () => void;
  projectOptions: {
    id: string;
    name: string;
    imageUrl: string;
  }[];
  memberOptions: {
    id: string;
    name: string;
  }[];
  initialValues: Epic;
  currentMember?: {
    id: string;
    role: MemberRole;
    userId: string;
  };
}

export const EditEpicForm = ({
  onCancel,
  memberOptions,
  projectOptions,
  initialValues,
  currentMember,
}: EditEpicFormProps) => {
  const workspaceId = useWorkspaceId();
  const { mutate, isPending } = useUpdateEpic();
  const { mutate: deleteEpic, isPending: isDeletingEpic } = useDeleteEpic();

  const [DeleteDialog, confirmDelete] = useConfirm(
    "Delete Epic",
    "This action cannot be undone. This will permanently delete the epic and all related tasks.",
    "destructive"
  );

  const isAdmin = currentMember?.role === MemberRole.ADMIN;
  
  const form = useForm<z.infer<typeof updateEpicSchema>>({
    resolver: zodResolver(updateEpicSchema),
    defaultValues: {
      name: initialValues.name,
      description: initialValues.description || "",
      projectId: initialValues.projectId || "",
      assigneeId: initialValues.assigneeId || "",
      dueDate: initialValues.dueDate ? new Date(initialValues.dueDate) : undefined,
      labels: initialValues.labels || [],
    },
  });

  const onSubmit = (values: z.infer<typeof updateEpicSchema>) => {
    mutate(
      {
        json: values,
        param: { epicId: initialValues.id },
      },
      {
        onSuccess: () => {
          onCancel?.();
        },
      }
    );
  };

  const handleDelete = async () => {
    const ok = await confirmDelete();
    if (!ok) return;

    deleteEpic(
      {
        param: { epicId: initialValues.id },
      },
      {
        onSuccess: () => {
          onCancel?.();
        },
      }
    );
  };

  return (
    <>
      <DeleteDialog />
      <Card className="size-full border-none shadow-none">
        <CardHeader className="flex py-1">
          <CardTitle className="text-xl font-bold">Edit Epic</CardTitle>
        </CardHeader>
      <div className="px-2 py-1">
        <DottedSeparator />
      </div>
      <CardContent className="px-3">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} onKeyDown={(e) => {
            // Prevent form submission when Enter is pressed in tag inputs
            if (e.key === 'Enter' && e.target instanceof HTMLElement) {
              const isInTagInput = e.target.closest('[data-tag-input]');
              if (isInTagInput) {
                e.preventDefault();
                return;
              }
            }
          }}>
            <div className="flex flex-col gap-y-2">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Epic name</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        placeholder="Enter epic name"
                        autoComplete="off"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <Textarea
                        {...field}
                        placeholder="Enter epic description..."
                        className="min-h-[120px]"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="dueDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Due date (Optional)</FormLabel>
                    <FormControl>
                      <DatePicker {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="assigneeId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Epic Owner</FormLabel>
                    <Select
                      defaultValue={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Select epic owner" />
                        </SelectTrigger>
                      </FormControl>
                      <FormMessage />
                      <SelectContent>
                        {memberOptions.map((member) => (
                          <SelectItem key={member.id} value={member.id}>
                            <div className="flex items-center gap-x-2">
                              <MemberAvatar className="size-6" name={member.name} />
                              {member.name}
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="projectId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Project</FormLabel>
                    <Select
                      defaultValue={field.value}
                      onValueChange={field.onChange}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Select project" />
                        </SelectTrigger>
                      </FormControl>
                      <FormMessage />
                      <SelectContent>
                        {projectOptions.map((project) => (
                          <SelectItem key={project.id} value={project.id}>
                            <div className="flex items-center gap-x-2">
                              <ProjectAvatar
                                className="size-6"
                                name={project.name}
                                image={project.imageUrl}
                              />
                              {project.name}
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="labels"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Labels</FormLabel>
                    <FormControl>
                      <TagsInput
                        value={field.value || []}
                        onChange={field.onChange}
                        placeholder="Add labels..."
                        disabled={isPending}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <DottedSeparator className="py-7" />
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-x-2">
                <Button
                  type="button"
                  size="lg"
                  variant="outline"
                  onClick={onCancel}
                  disabled={isPending || isDeletingEpic}
                  className={cn(!onCancel && "invisible")}
                >
                  Cancel
                </Button>
                {isAdmin && (
                  <Button
                    type="button"
                    size="lg"
                    variant="destructive"
                    onClick={handleDelete}
                    disabled={isPending || isDeletingEpic}
                  >
                    <Trash className="size-4 mr-2" />
                    Delete Epic
                  </Button>
                )}
              </div>
              <Button disabled={isPending || isDeletingEpic} type="submit" size="lg">
                Save Changes
              </Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
    </>
  );
}; 