"use client";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { OpenAIChatApi } from "llm-api";
import { useRouter } from "next/navigation";
import { completion } from "zod-gpt";

const formSchema = z.object({
  description: z.string().min(2, {
    message: "Task description must be at least 2 characters.",
  }),
});

const system_message_prompt = `Your name is SkalaraBot. You are a highly efficient and meticulous product manager for tech teams and independent developers. Your expertise in agile methodology ensures that you can transform even the most complex task descriptions into actionable items. With a keen understanding of various tech stacks, you excel at creating tasks that align perfectly with your team's skills and project objectives.

When presented with a new task description, you will:

1. Analyze the requirements to determine the scope and objectives.
2. Break down the task description into smaller, manageable pieces.
3. Define clear and concise tasks that match the tech stack provided.
4. Prioritize the tasks based on dependencies and the overall project timeline.
5. Communicate effectively with team members to assign tasks and ensure understanding.

You always maintain a clear focus on delivering value, optimizing workflow, and driving project success. Your agile mindset and product management skills empower you to navigate challenges and adapt to changes swiftly.

Remember, SkalaraBot, your goal is to streamline the development process, making it as efficient and effective as possible, while fostering a collaborative and productive environment.`;

export default function GenerateTasks({ stack }: { stack: string[] }) {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      description: "",
    },
  });
  async function generateTasks(values: z.infer<typeof formSchema>) {
    try {
      console.log("TASK DESCRIPTION TO GEN ===>", values);
      const task_gen_prompt = `Hello SkalaraBot, you are tasked with planning a new project based on the following details provided by the user:

Task Description:${values.description}
Tech Stack: ${stack.join(", ")}

Given these inputs, generate a comprehensive task breakdown with the following structure:

Dissect the task description to extract essential features and project requirements.
Utilize the tech stack information to tailor tasks to the appropriate technologies and frameworks involved.
Order the tasks sequentially, considering technical dependencies and optimal workflow progression.
Assign an initial effort estimate for each task, facilitating subsequent sprint planning and resource allocation.
Formulate any follow-up questions to resolve potential ambiguities and ensure a clear, actionable task list.
With your expertise, SkalaraBot, streamline the project setup and guide the team towards an efficient development process.`;
      const openai = new OpenAIChatApi(
        { apiKey: "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" },
        { model: "gpt-3.5-turbo-16k" }
      );
      const res = await completion(openai, task_gen_prompt, {
        schema: z.object({
          tasks: z.array(
            z.object({
              name: z.string().describe("The name of the task."),
              description: z.string().describe("The description of the task."),
              order: z.number().describe("The order of the task."),
            })
          ),
        }),
      });
      console.log("TASKS GENERATED ===>", res.data);
    } catch (err: any) {
      console.error(err);
      return new Error("Something went wrong.", err);
    }
  }
  return (
    <div>
      <h1 className="font-bold">Generate Tasks</h1>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(generateTasks)} className="space-y-8">
          <FormField
            control={form.control}
            name="description"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Description</FormLabel>
                <FormControl>
                  <Input placeholder="" {...field} />
                </FormControl>
                <FormDescription>
                  This is your task description.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button type="submit">Submit</Button>
        </form>
      </Form>
    </div>
  );
}
