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 { CreateWorkspace } from "@/components/create-workspace";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

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

async function fetchWorkspaces() {
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);

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

  try {
    const profile_with_workspaces = await prisma.profile.findUnique({
      where: {
        id: session.user.id,
      },
      include: {
        profile_workspace: {
          include: {
            workspace: true,
          },
        },
      },
    });

    if (!profile_with_workspaces) throw new Error("No profile found.");

    const workspaces = profile_with_workspaces.profile_workspace.map((pw) => ({
      ...pw.workspace,
      id: String(pw.workspace.id),
    }));

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

export async function WorkspaceSelector({
  workspaceID,
}: {
  workspaceID?: string;
}) {
  const workspaces = await fetchWorkspaces();

  if (!workspaces) {
    return (
      <div>
        <h1>No workspaces</h1>
        <CreateWorkspace />
      </div>
    );
  }

  return (
    <div className="h-screen max-h-screen flex flex-col p-4 space-y-6 items-center border-r">
      <Link href="/">
        <svg
          fill="#7C3AED"
          width="32px"
          height="32px"
          viewBox="0 0 15 15"
          version="1.1"
          id="circle"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path d="M14,7.5c0,3.5899-2.9101,6.5-6.5,6.5S1,11.0899,1,7.5S3.9101,1,7.5,1S14,3.9101,14,7.5z" />
        </svg>
      </Link>
      <div className="flex flex-col space-y-4">
        {workspaces?.map((workspace) => (
          <Link href={`/w/${workspace.id}`} key={workspace.id}>
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger>
                  <Avatar
                    className={cn(
                      "rounded-md ring-offset-background hover:ring-2 hover:ring-ring hover:ring-offset-2",
                      workspace.id === workspaceID
                        ? "ring-2 ring-ring ring-offset-2"
                        : ""
                    )}
                  >
                    <AvatarImage src="" />
                    <AvatarFallback className="rounded-md">
                      {workspace.name.toUpperCase().slice(0, 2)}
                    </AvatarFallback>
                  </Avatar>
                </TooltipTrigger>
                <TooltipContent side="right" sideOffset={10}>
                  {workspace.name}
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </Link>
        ))}
        <CreateWorkspace />
      </div>
    </div>
  );
}
