import { Link, useLocation } from "react-router";
import { Grid2X2, MessageSquare } from "lucide-react";
import { cn } from "@/lib/utils";
import { workspaceColor, workspaceInitial } from "./shared";
import { type WorkspaceResponse } from "@/client";

export function WorkspaceAvatar({ workspace }: { workspace?: WorkspaceResponse }) {
  const name = workspace?.name ?? "Workspace";
  return (
    <span
      className={cn(
        "grid size-9 shrink-0 place-items-center overflow-hidden rounded-full bg-gradient-to-br text-sm font-semibold text-white",
        workspaceColor(name),
      )}
    >
      {workspace?.avatar_url ? (
        <img alt="" className="size-full object-cover" src={workspace.avatar_url} />
      ) : (
        workspaceInitial(name)
      )}
    </span>
  );
}

export function WorkspaceModeSwitch({ projectName }: { projectName: string }) {
  const location = useLocation();
  const modes = [
    {
      label: "Channel",
      to: `/${projectName}/channel`,
      icon: <MessageSquare className="size-4" />,
      activePaths: [`/${projectName}/channel`, `/${projectName}/chat`],
    },
    {
      label: "Workplan",
      to: `/${projectName}/workplan/chat`,
      icon: <Grid2X2 className="size-4" />,
      activePaths: [
        `/${projectName}/repos`,
        `/${projectName}/issues`,
        `/${projectName}/settings`,
        `/${projectName}/workplan`,
      ],
    },
  ];

  return (
    <nav
      aria-label="Workspace mode"
      className="grid grid-cols-2 gap-1 rounded-xl bg-muted/70 p-1"
    >
      {modes.map((mode) => {
        const active = mode.activePaths.some(
          (path) => location.pathname === path || location.pathname.startsWith(`${path}/`),
        );

        return (
          <Link
            className={cn(
              "flex h-8 items-center justify-center gap-2 rounded-md text-sm font-semibold text-muted-foreground transition-colors hover:text-foreground",
              active && "bg-card text-foreground shadow-sm ring-1 ring-border",
            )}
            key={mode.to}
            to={mode.to}
          >
            {mode.icon}
            <span className="truncate">{mode.label}</span>
          </Link>
        );
      })}
    </nav>
  );
}