import { projectRepos } from "@/client";
import { SidebarSystem } from "@/components/layout/sidebar-system";
import { SidebarUser } from "@/components/layout/sidebar-user";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useRepo } from "@/contexts";
import { useQuery } from "@tanstack/react-query";
import {
  ChevronLeft,
  ChevronRight,
  ChevronsUpDown,
  FileText,
  FolderGit2,
  GitBranch,
  GitCommit,
  GitMerge,
  Settings,
  Tag,
  Users,
} from "lucide-react";
import { useMemo, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";

type SidebarItem = {
  title: string;
  icon: React.ReactNode;
  url: string;
  adminOnly?: boolean;
  exact?: boolean;
};

export const RepoSidebar = () => {
  const repo = useRepo();
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);

  const namespace = repo?.namespace || "";
  const repoName = repo?.repo_name || "";

  const { data: projectReposDataRaw } = useQuery({
    queryKey: ["projectRepos", namespace],
    queryFn: async () => {
      const resp = await projectRepos({ path: { project_name: namespace } });
      return resp.data?.data?.items ?? [];
    },
    enabled: !!namespace,
    staleTime: 5 * 60 * 1000,
  });

  const projectReposData = (Array.isArray(projectReposDataRaw) ? projectReposDataRaw : []) as Array<{ repo_name: string }>;

  const items: SidebarItem[] = useMemo(
    () => [
      {
        title: "Overview",
        icon: <FolderGit2 className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}`,
        exact: true,
      },
      {
        title: "Files",
        icon: <FileText className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}/files`,
      },
      {
        title: "Commits",
        icon: <GitCommit className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}/commits`,
      },
      {
        title: "Branches",
        icon: <GitBranch className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}/branches`,
      },
      {
        title: "Pull Requests",
        icon: <GitMerge className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}/pull-requests`,
      },
      { title: "Tags", icon: <Tag className="h-4 w-4" />, url: `/repository/${namespace}/${repoName}/tags` },
      {
        title: "Contributors",
        icon: <Users className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}/contributors`,
      },
      {
        title: "Settings",
        icon: <Settings className="h-4 w-4" />,
        url: `/repository/${namespace}/${repoName}/settings`,
        adminOnly: true,
      },
    ],
    [namespace, repoName],
  );

  return (
    <TooltipProvider>
      <aside
        className={cn(
          "hidden md:flex h-full flex-col border-r bg-background transition-all duration-200",
          collapsed ? "w-16" : "w-64",
        )}
      >
        {/* Repo switcher + collapse toggle */}
        <div className="border-b px-2 h-12 flex items-center gap-2">
          {!collapsed && (
            <DropdownMenu>
              <DropdownMenuTrigger className="h-auto flex-1 justify-start px-1 py-1 overflow-hidden inline-flex items-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground border-transparent">
                <div className="flex min-w-0 items-center gap-3 overflow-hidden">
                  <Avatar className="h-8 w-8">
                    <AvatarFallback>{repoName.charAt(0).toUpperCase()}</AvatarFallback>
                  </Avatar>
                  <div className="min-w-0 flex-1 truncate text-left text-sm font-semibold">
                    {repoName}
                  </div>
                  <ChevronsUpDown className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                </div>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="start" className="w-64">
                <DropdownMenuGroup>
                  <DropdownMenuLabel>Switch repository</DropdownMenuLabel>
                </DropdownMenuGroup>
                <DropdownMenuSeparator />
                {projectReposData.map((item) => (
                  <DropdownMenuItem
                    key={item.repo_name}
                    onClick={() =>
                      navigate(
                        `/repository/${encodeURIComponent(namespace)}/${encodeURIComponent(item.repo_name)}`,
                      )
                    }
                    className={cn(item.repo_name === repoName && "bg-accent")}
                  >
                    <span className="truncate">{item.repo_name}</span>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
          <Button
            variant="ghost"
            size="icon"
            className="flex-shrink-0"
            onClick={() => setCollapsed(!collapsed)}
          >
            {collapsed ? <ChevronRight /> : <ChevronLeft />}
          </Button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 p-2">
          <ul className="space-y-1">
            {items.map((item) => {
              const isActive = item.exact
                ? location.pathname === item.url
                : location.pathname === item.url || location.pathname.startsWith(`${item.url}/`);
              const content = (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => navigate(item.url)}
                  className={cn(
                    "w-full gap-3",
                    collapsed ? "justify-center" : "justify-start",
                    isActive && "bg-primary/10 text-primary",
                  )}
                >
                  {item.icon}
                  {!collapsed && item.title}
                </Button>
              );
              return (
                <li key={item.title}>
                  {collapsed ? (
                    <Tooltip>
                      <TooltipTrigger>{content}</TooltipTrigger>
                      <TooltipContent side="right">{item.title}</TooltipContent>
                    </Tooltip>
                  ) : (
                    content
                  )}
                </li>
              );
            })}
          </ul>
        </nav>

        {/* Bottom: system + user */}
        <div className="p-2 border-t">
          <SidebarSystem collapsed={collapsed} />
          <SidebarUser collapsed={collapsed} />
        </div>
      </aside>
    </TooltipProvider>
  );
};
