"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { Project } from "@/types/models";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { X } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormDescription,
  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";
import { OpenAIChatApi } from "llm-api";
import { completion } from "zod-gpt";

const projectSchema = z.object({
  title: z.string().min(3, "Title must be at least 3 characters"),
  description: z.string().min(10, "Description must be at least 10 characters"),
  github: z.string().url("Invalid URL").optional(),
  stack: z.string().array(),
});

export default function Projects() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [stackInput, setStackInput] = useState("");
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [features, setFeatures] = useState<string[]>([]);
  const [step, setStep] = useState(0);
  const [progress, setProgress] = useState(0);
  const form = useForm<z.infer<typeof projectSchema>>({
    resolver: zodResolver(projectSchema),
    defaultValues: {
      title: "",
      description: "",
      github: "",
      stack: [],
    },
  });

  const { setValue } = form;

  const fetchProjects = async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/projects");
      if (!res.ok) throw new Error("HTTP status " + res.status);
      const data = await res.json();
      setProjects(data);
      setLoading(false);
    } catch (err) {
      console.error("Failed to fetch projects:", err);
    }
  };

  useEffect(() => {
    fetchProjects();
  }, []);

  async function handleSubmit(values: z.infer<typeof projectSchema>) {
    try {
      // 1. Create a new project
      const res = await fetch("/api/projects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      if (!res.ok) throw new Error("HTTP status " + res.status);
      const newProject = await res.json();
      setProjects([...projects, newProject]);

      // 2. Initialize OpenAI client
      setStep(1);
      const openai = new OpenAIChatApi(
        {
          apiKey: "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",
        },
        { model: "gpt-3.5-turbo-16k" }
      );

      // 3. Generate features
      const prompt = `Based on the following project information, generate features for this tech project:
    Project Description: ${newProject.description}
    Tech Stack: ${newProject.stack.join(", ")}`;
      const featuresRes = await completion(openai, prompt, {
        schema: z.object({
          features: z.array(z.object({ feature: z.string() })),
        }),
      });
      const features = featuresRes.data.features.map((f) => f.feature);
      setFeatures(features);
      setStep(2);
    } catch (err) {
      console.error("Failed to create project:", err);
    }
  }

  async function handleGenerateTasks() {
    try {
      // Move to the task generation step and reset progress
      setStep(3);
      setProgress(0);

      // Get the newly created project
      const newProject = projects[projects.length - 1];

      // Initialize OpenAI client
      const openai = new OpenAIChatApi(
        {
          apiKey: "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",
        },
        { model: "gpt-3.5-turbo-16k" }
      );

      // Generate tasks for each feature
      const taskList = [];
      for (let i = 0; i < features.length; i++) {
        const feature = features[i];
        const taskPrompt = `
      Given the following project description, feature description, and tech stack, generate a list of tasks needed to implement the feature:
      Project: ${newProject.title}
      Feature: ${feature}
      Tech Stack: ${newProject.stack.join(", ")}`;

        // Get tasks for the current feature
        const tasksRes = await completion(openai, taskPrompt, {
          schema: z.object({ tasks: z.array(z.object({ task: z.string() })) }),
        });

        // Add the tasks to the task list
        taskList.push(...tasksRes.data.tasks);

        // Update the progress
        setProgress(((i + 1) / features.length) * 100);
      }

      // Post the generated tasks to the project
      const taskRes = await fetch(`/api/projects/${newProject.id}/tasks`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(taskList),
      });
      if (!taskRes.ok) throw new Error("HTTP status " + taskRes.status);

      // Log the created tasks
      const createdTasks = await taskRes.json();
      console.log("Tasks created:", createdTasks);

      // Close the dialog
      setOpen(false);
    } catch (err) {
      console.error("Failed to generate tasks:", err);
    }
  }

  const keyHandler = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" || e.key === "Tab") {
      e.preventDefault();
      setValue("stack", [...form.getValues("stack"), stackInput]);
      setStackInput("");
    }
  };

  return (
    <div>
      <h1>Projects</h1>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger className={buttonVariants({ variant: "default" })}>
          Open
        </DialogTrigger>
        {step === 0 && (
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Add Project</DialogTitle>
              <DialogDescription>
                <Form {...form}>
                  <form
                    onSubmit={form.handleSubmit(handleSubmit)}
                    className="space-y-8"
                  >
                    <FormField
                      control={form.control}
                      name="title"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Project Title</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="description"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Project Description</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="github"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Github Repository URL</FormLabel>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name="stack"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Tech Stack</FormLabel>
                          <FormControl>
                            <Input
                              value={stackInput}
                              onChange={(e) => setStackInput(e.target.value)}
                              onKeyDown={keyHandler}
                            />
                          </FormControl>
                          <FormDescription>
                            {form.getValues("stack").map((stack) => (
                              <Badge
                                key={stack}
                                className="mr-2 font-light"
                                variant="outline"
                              >
                                {stack}{" "}
                                <X
                                  className="inline font-light"
                                  size={16}
                                  onClick={() =>
                                    setValue(
                                      "stack",
                                      form
                                        .getValues("stack")
                                        .filter((s) => s !== stack)
                                    )
                                  }
                                />
                              </Badge>
                            ))}
                          </FormDescription>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <Button type="submit">Submit</Button>
                  </form>
                </Form>
              </DialogDescription>
            </DialogHeader>
          </DialogContent>
        )}
        {step === 1 && (
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Generating Features</DialogTitle>
              <DialogDescription>
                <p>Generating features for your project...</p>
              </DialogDescription>
            </DialogHeader>
          </DialogContent>
        )}
        {step === 2 && (
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Features Generated</DialogTitle>
              <DialogDescription>
                <div>
                  {features.map((feature, index) => (
                    <Badge key={index} variant="outline">
                      {feature}{" "}
                      <X
                        size={16}
                        onClick={() =>
                          setFeatures(features.filter((_, i) => i !== index))
                        }
                      />
                    </Badge>
                  ))}
                </div>
                <Button onClick={handleGenerateTasks}>Generate Tasks</Button>
              </DialogDescription>
            </DialogHeader>
          </DialogContent>
        )}
        {step === 3 && (
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Generating Tasks</DialogTitle>
              <DialogDescription>
                <Progress value={progress} />
              </DialogDescription>
            </DialogHeader>
          </DialogContent>
        )}
      </Dialog>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <div>
          {projects.map((project) => (
            <div key={project.id}>
              <h2>
                <Link href={`/projects/${project.id}`}>{project.title}</Link>
              </h2>
              <p>{project.description}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
