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 { CreateProject } from "@/components/create-project";
import { Button } from "@/components/ui/button";
import { ChevronDownIcon } from "@radix-ui/react-icons";
import { cn } from "@/lib/utils";

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

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

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

  try {
    // TODO: fetch all projects that are part of this workspace, and that the user is a part of.
    const projects = await prisma.project.findMany({
      where: {
        workspace_id: BigInt(workspaceID),
        profile_project: {
          some: {
            profile_id: session.user.id,
          },
        },
      },
    });

    const res = projects.map((project) => ({
      ...project,
      id: String(project.id),
    }));

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

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

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

  try {
    const workspace = await prisma.workspace.findUnique({
      where: {
        id: BigInt(workspaceID),
      },
    });

    if (!workspace) throw new Error("Workspace not found.");

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

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

export async function WorkspaceSidebar({
  workspaceID,
  projectID,
}: {
  workspaceID: string;
  projectID?: string;
}) {
  const workspace = await getWorkspace(workspaceID);
  const projects = await fetchProjects(workspaceID);

  console.log("PROJECTS", projects);
  console.log("WORKSPACE", workspace);

  if (!workspace) {
    return (
      <div>
        <h1>Workspace not found.</h1>
      </div>
    );
  }

  if (projects?.length == 0 || !projects) {
    return (
      <div>
        <h1>No projects</h1>
        <CreateProject />
      </div>
    );
  }

  return (
    <div className="h-screen h-max-screen flex flex-col border-r w-56">
      <div className="w-full flex flex-col justify-center items-center p-4 border-b">
        <h1 className="font-medium">{workspace.name}</h1>
      </div>
      <div className="h-full flex flex-col justify-between">
        <div>
          <h2 className="py-2 pl-2 font-medium">Projects</h2>
          <div className="w-full">
            {projects.map((project) => (
              <div key={project.id} className="">
                <Button
                  asChild
                  variant="ghost"
                  className={cn(
                    "w-full justify-start rounded-none h-7 font-normal",
                    project.id === projectID ? "bg-secondary/80" : ""
                  )}
                >
                  <Link href={`/w/${workspaceID}/p/${project.id}`} className="">
                    {project.name}
                  </Link>
                </Button>
              </div>
            ))}
          </div>
        </div>
        <div className="w-full p-4">
          <CreateProject className="w-full" />
        </div>
      </div>
    </div>
  );
}
