import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { Database } from "@/types/supabase";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { NextResponse, NextRequest } from "next/server";
import prisma from "@/lib/prisma";
import { WorkspaceSidebar } from "@/components/workspace-sidebar";
import { ThemeToggle } from "@/components/theme-toggle";
import KanbanBoard from "@/components/kanban/board";
import { Button } from "@/components/ui/button";
import { GenerateProject } from "@/components/generate-project";
import Tasks from "@/components/tasks";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { FeatureList } from "@/components/feature-list";

async function getSession(supabase: any) {
  const {
    data: { session },
  } = await supabase.auth.getSession();
  return session;
}

// async function getProject(projectID: string) {
//   const supabase = createServerComponentClient<Database>({ cookies });
//   const session = await getSession(supabase);

//   if (!session) redirect("/auth");

//   try {
//     // prisma function to get project by projectID if user is part of the project
//     const project = await prisma.project.findFirst({
//       where: {
//         id: BigInt(projectID),
//         profile_project: {
//           some: {
//             profile_id: session.user.id,
//           },
//         },
//       },
//       include: {
//         task: true,
//       },
//     });

//     if (!project) {
//       return NextResponse.json({ error: "not_found" }, { status: 404 });
//     }

//     const serialized_tasks = project.task.map((task) => ({
//       ...task,
//       id: task.id.toString(),
//       project_id: task.project_id?.toString(),
//       feature_id: task.feature_id?.toString(),
//     }));

//     const convertTaskBigIntsToString = (task: any) => {
//       return {
//         ...task,
//         id: task.id.toString(),
//         project_id: task.project_id.toString(),
//         feature_id: task.feature_id.toString(),
//         order: task.order.toString(),
//       };
//     };

//     const res = {
//       ...project,
//       id: project.id.toString(),
//       workspace_id: project.workspace_id.toString(),
//       task: serialized_tasks.map(convertTaskBigIntsToString),
//     };

//     console.log("RES", project.task);

//     return NextResponse.json(res, { status: 200 });
//   } catch (err) {
//     console.error(err);
//   }
// }
async function getProject(projectID: string) {
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);

  if (!session) redirect("/auth");

  try {
    // const project = await prisma.project.findFirst({
    //   where: {
    //     id: BigInt(projectID),
    //     profile_project: {
    //       some: {
    //         profile_id: session.user.id,
    //       },
    //     },
    //   },
    //   include: {
    //     task: {
    //       include: {
    //         feature: true, // Assuming 'feature' is correctly named relation
    //       },
    //     },
    //   },
    // });

    // if (!project) {
    //   return NextResponse.json({ error: "not_found" }, { status: 404 });
    // }

    // // Serialize BigInts and include project and feature information
    // const serializedProject = {
    //   id: project.id.toString(),
    //   workspace_id: project.workspace_id.toString(),
    //   created_at: project.created_at,
    //   name: project.name,
    //   description: project.description,
    //   stack: project.stack,
    //   questions: project.questions,
    //   tasks: project.task.map(({ feature, ...task }) => ({
    //     ...task,
    //     id: task.id.toString(),
    //     project_id: task.project_id?.toString(),
    //     feature_id: feature?.id.toString(),
    //     feature_name: feature?.name, // Assume feature is nullable
    //     feature_description: feature?.description, // Assume feature is nullable
    //     // ...include other task fields that may be BigInt or require serialization
    //   })),
    // };

    // console.log("Serialized Project", serializedProject);

    // return NextResponse.json(serializedProject, { status: 200 });
    const project = await prisma.project.findFirst({
      where: {
        id: BigInt(projectID),
        // ... other conditions
      },
      include: {
        task: {
          include: {
            feature: true,
          },
        },
      },
    });

    if (!project) {
      return NextResponse.json({ error: "not_found" }, { status: 404 });
    }

    // Map tasks to conform to the taskSchema
    const tasksWithDetails = project.task.map((task) => {
      return {
        id: task.id.toString(),
        name: task.name,
        description: task.description,
        project_id: project.id.toString(),
        project_name: project.name,
        project_description: project.description,
        project_stack: project.stack,
        feature_id: task.feature_id?.toString() || null,
        feature_name: task.feature?.name || null,
        feature_description: task.feature?.description || null,
        status: task.status,
        priority: task.priority || null,
        order: task.order, // Convert order to number if it exists
        due_date: task.due_date ? task.due_date.toISOString() : null, // Convert to ISO string if due_date exists
        assignee: task.assignee || null,
        // Add serialization for any other fields that are required by the task schema
      };
    });

    const response = {
      id: project.id.toString(),
      name: project.name,
      description: project.description,
      stack: project.stack,
      workspace_id: project.workspace_id.toString(),
      // ...include other project-level details as needed
      tasks: tasksWithDetails, // Include the detailed tasks list
    };

    console.log("Project with Tasks", response);

    return NextResponse.json(response, { status: 200 });
  } catch (err) {
    console.error(err);
    return NextResponse.json({ error: "server_error" }, { status: 500 });
  }
}

export default async function Project({
  params: { workspaceID, projectID },
}: {
  params: { workspaceID: string; projectID: string };
}) {
  const raw_project = await getProject(projectID);
  console.log("RAW PROJECT", raw_project);
  if (raw_project?.status == 404) {
    return (
      <div>
        <h1>Project not found.</h1>
      </div>
    );
  }

  if (!raw_project) {
    return (
      <div>
        <h1>Something went wrong.</h1>
      </div>
    );
  }

  const project = await raw_project.json();
  console.log("AWAITED PROJECT", project);

  return (
    <div className="w-full h-full flex flex-col">
      <div className="w-full p-4 border-b flex flex-row justify-between items-center">
        <h1 className="text-lg font-semibold">{project.name}</h1>
        <div className="flex flex-row justify-center items-center space-x-2">
          <Dialog>
            <Button asChild variant="outline">
              <DialogTrigger>View Features</DialogTrigger>
            </Button>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Features</DialogTitle>
              </DialogHeader>
              <FeatureList projectID={projectID} />
            </DialogContent>
          </Dialog>
          <ThemeToggle />
        </div>
      </div>
      <GenerateProject
        project_name={project.name}
        project_description={project.description}
        project_stack={project.stack}
      />
      {/* <KanbanBoard /> */}
      <div className="p-12 max-h-full">
        <Tasks tasks={project.tasks ? project.tasks : []} />
      </div>
    </div>
  );
}
