"use client";
import { useState, useEffect } from "react";
import { Project, Task } from "@/types/models";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";

const taskSchema = z.object({
  description: z.string().min(10, "Description must be at least 10 characters"),
  status: z.string().optional(),
  priority: z.string().optional(),
  dueDate: z.date().optional(),
  tags: z.array(z.string()).optional(),
});

export default function Project({ params }: { params: { id: string } }) {
  const [project, setProject] = useState<Project | undefined>();
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [task, setTask] = useState<Task | undefined>();
  const form = useForm<z.infer<typeof taskSchema>>({
    resolver: zodResolver(taskSchema),
    defaultValues: {
      description: "",
      status: "",
      priority: "",
      dueDate: undefined,
    },
  });

  useEffect(() => {
    if (params.id) {
      fetch(`/api/projects/${params.id}`)
        .then((res) => {
          if (!res.ok) throw new Error("HTTP status " + res.status);
          return res.json();
        })
        .then((data) => {
          setProject(data);
          setLoading(false);
        })
        .catch((err) => console.error("Failed to fetch project:", err));
    }
  }, [params.id]);

  async function handleSubmit(values: z.infer<typeof taskSchema>) {
    try {
      const res = await fetch(`/api/projects/${params.id}/tasks`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      });

      if (!res.ok) throw new Error("HTTP status " + res.status);
      const newTask = await res.json();
      setProject((prevProject) => {
        if (!prevProject) return;

        const prevTasks = prevProject.tasks || [];
        return {
          ...prevProject,
          tasks: [...prevTasks, newTask],
        };
      });

      setOpen(false);
    } catch (err) {
      console.error("Failed to create task:", err);
    }
  }

  if (loading) return <p>Loading...</p>;
  if (!project) return <p>No project found.</p>;

  return (
    <Sheet>
      <div>
        <h2>{project.title}</h2>
        <p>{project.description}</p>
        <div>
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger className={buttonVariants({ variant: "default" })}>
              Add Task
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Add Task</DialogTitle>
                <DialogDescription>
                  <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)}>
                      <FormField
                        control={form.control}
                        name="description"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Task Description</FormLabel>
                            <FormControl>
                              <Input {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="status"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Task Status</FormLabel>
                            <FormControl>
                              <Input {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="priority"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Task Priority</FormLabel>
                            <FormControl>
                              <Input {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <Button type="submit">Submit</Button>
                    </form>
                  </Form>
                </DialogDescription>
              </DialogHeader>
            </DialogContent>
          </Dialog>
          <h3>Tasks</h3>
          {project.tasks?.map((task: Task) => (
            <div key={task.id}>
              <SheetTrigger onClick={() => console.log("hey")}>
                {task.description}
              </SheetTrigger>
            </div>
          ))}
        </div>
        <SheetContent>
          <SheetHeader>
            <SheetTitle>Are you sure absolutely sure?</SheetTitle>
            <SheetDescription>
              This action cannot be undone. This will permanently delete your
              account and remove your data from our servers.
            </SheetDescription>
          </SheetHeader>
        </SheetContent>
      </div>
    </Sheet>
  );
}
