import { FeatureList } from "@/components/feature-list";
import { TaskList } from "@/components/task-list";
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { Database } from "@/types/supabase";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { CreateFeature } from "@/components/create-feature";
import { NextResponse } from "next/server";

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 {
    const project = await prisma.project.findUnique({
      where: {
        id: BigInt(projectID),
      },
    });

    if (!project) return undefined;

    const res = {
      ...project,
      id: String(project.id),
      workspace_id: String(project.workspace_id),
    };

    return res;
  } catch (err) {
    console.error(err);
    return;
  }
}

export default async function Project({
  params: { projectID, workspaceID },
}: {
  params: { projectID: string; workspaceID: string };
}) {
  const project = await getProject(projectID);
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);
  if (!project)
    return (
      <div className="flex h-screen">
        <h1 className="m-auto">Project not found.</h1>
      </div>
    );

  if (
    !(await prisma.profile_project.findFirst({
      where: {
        profile_id: session.user.id,
        project_id: BigInt(projectID),
      },
    }))
  ) {
    return (
      <div className="flex h-screen">
        <h1 className="m-auto">You are not a member of this project.</h1>
      </div>
    );
  }

  return (
    <div>
      <h1>Project: {projectID}</h1>
      <h2>Workspace: {workspaceID}</h2>
      <h2>Project Name: {project?.name}</h2>
      <h2>Project Description: {project?.description}</h2>
      <h2>Tech Stack: {project?.stack.join(", ")}</h2>

      <FeatureList
        workspaceID={workspaceID}
        projectID={projectID}
        project_name={project ? project.name : ""}
        project_description={project?.description ? project.description : ""}
        tech_stack={project ? project.stack : []}
      />
      <TaskList
        workspaceID={workspaceID}
        projectID={projectID}
        project_name={project ? project.name : ""}
        project_description={project?.description ? project.description : ""}
        tech_stack={project ? project.stack : []}
      />
    </div>
  );
}
