"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import {
  Activity,
  BarChart3,
  Bot,
  Boxes,
  Building2,
  CheckCircle2,
  CircleDot,
  Folder,
  FolderGit,
  KeyRound,
  LayoutGrid,
  Network,
  Settings,
  Store,
  Tags,
  TerminalSquare,
} from "lucide-react";

import { ApiError } from "@/api/mutator";
import {
  type healthzHealthzGetResponse,
  useHealthzHealthzGet,
} from "@/api/generated/default/default";
import { useAuth } from "@/auth/clerk";
import { useOrganizationMembership } from "@/lib/use-organization-membership";
import { cn } from "@/lib/utils";

type NavTone = "blue" | "cyan" | "emerald" | "violet" | "amber" | "rose";

const iconToneClass: Record<NavTone, string> = {
  blue: "bg-blue-500/15 text-blue-300 ring-blue-400/20",
  cyan: "bg-cyan-500/15 text-cyan-300 ring-cyan-400/20",
  emerald: "bg-emerald-500/15 text-emerald-300 ring-emerald-400/20",
  violet: "bg-violet-500/15 text-violet-300 ring-violet-400/20",
  amber: "bg-amber-500/15 text-amber-300 ring-amber-400/20",
  rose: "bg-rose-500/15 text-rose-300 ring-rose-400/20",
};

const sectionHeaderClass =
  "px-3 text-[13px] font-bold uppercase tracking-[0.18em] text-[color:var(--text)]";

const navItemClass = (active: boolean) =>
  cn(
    "group relative flex items-center gap-3 rounded-lg px-3 py-2.5 text-[15px] font-semibold text-[color:var(--text-muted)] transition duration-200",
    "before:absolute before:inset-y-2 before:left-0 before:w-1 before:rounded-full before:bg-transparent before:transition",
    active
      ? "bg-[color:var(--accent-soft)] text-[color:var(--text)] shadow-sm before:bg-[color:var(--accent)]"
      : "hover:bg-[color:var(--surface-muted)] hover:text-[color:var(--text)] hover:before:bg-[color:var(--border-strong)]",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--accent)] focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--surface)]",
  );

const iconClass = (active: boolean, tone: NavTone) =>
  cn(
    "flex h-8 w-8 shrink-0 items-center justify-center rounded-md ring-1 transition duration-200",
    iconToneClass[tone],
    active &&
      "bg-[color:var(--accent)] text-[color:var(--primary-foreground)] ring-[color:var(--accent)]",
    !active && "group-hover:scale-105 group-hover:ring-[color:var(--accent)]",
  );

function isNavActive(pathname: string, href: string) {
  if (href === "/git-projects") {
    return (
      pathname === href ||
      pathname.startsWith("/git-projects/connections") ||
      pathname.startsWith("/git-projects/repositories")
    );
  }

  if (href === "/settings") {
    return (
      pathname === href ||
      (pathname.startsWith("/settings/") &&
        !pathname.startsWith("/settings/ai-providers"))
    );
  }

  return pathname === href || pathname.startsWith(`${href}/`);
}

function NavItem({
  href,
  label,
  icon,
  tone,
  active,
}: {
  href: string;
  label: string;
  icon: ReactNode;
  tone: NavTone;
  active: boolean;
}) {
  return (
    <Link
      href={href}
      className={navItemClass(active)}
      aria-current={active ? "page" : undefined}
    >
      <span className={iconClass(active, tone)}>{icon}</span>
      <span className="truncate">{label}</span>
    </Link>
  );
}

export function DashboardSidebar() {
  const pathname = usePathname();
  const { isSignedIn } = useAuth();
  const { isAdmin } = useOrganizationMembership(isSignedIn);
  const healthQuery = useHealthzHealthzGet<healthzHealthzGetResponse, ApiError>(
    {
      query: {
        refetchInterval: 30_000,
        refetchOnMount: "always",
        retry: false,
      },
      request: { cache: "no-store" },
    },
  );

  const okValue = healthQuery.data?.data?.ok;
  const systemStatus: "unknown" | "operational" | "degraded" =
    okValue === true
      ? "operational"
      : okValue === false
        ? "degraded"
        : healthQuery.isError
          ? "degraded"
          : "unknown";
  const statusLabel =
    systemStatus === "operational"
      ? "All systems operational"
      : systemStatus === "unknown"
        ? "System status unavailable"
        : "System degraded";
  const isActive = (href: string) => isNavActive(pathname, href);

  return (
    <aside className="fixed inset-y-0 left-0 z-40 flex w-[280px] -translate-x-full flex-col border-r border-[color:var(--border)] bg-[linear-gradient(180deg,var(--surface)_0%,var(--surface-muted)_100%)] pt-16 shadow-lg transition-transform duration-200 ease-in-out [[data-sidebar=open]_&]:translate-x-0 md:relative md:inset-auto md:z-auto md:w-[260px] md:translate-x-0 md:pt-0 md:shadow-none md:transition-none">
      <div className="flex-1 overflow-y-auto px-3 py-5">
        <nav className="space-y-5">
          <div>
            <p className={sectionHeaderClass}>Overview</p>
            <div className="mt-2 space-y-1.5">
              <NavItem
                href="/dashboard"
                label="Dashboard"
                icon={<BarChart3 className="h-4 w-4" />}
                tone="blue"
                active={isActive("/dashboard")}
              />
              <NavItem
                href="/activity"
                label="Live feed"
                icon={<Activity className="h-4 w-4" />}
                tone="cyan"
                active={isActive("/activity")}
              />
            </div>
          </div>

          <div>
            <p className={sectionHeaderClass}>Boards</p>
            <div className="mt-2 space-y-1.5">
              <NavItem
                href="/board-groups"
                label="Board groups"
                icon={<Folder className="h-4 w-4" />}
                tone="emerald"
                active={isActive("/board-groups")}
              />
              <NavItem
                href="/boards"
                label="Boards"
                icon={<LayoutGrid className="h-4 w-4" />}
                tone="blue"
                active={isActive("/boards")}
              />
              <NavItem
                href="/git-projects"
                label="Git projects"
                icon={<FolderGit className="h-4 w-4" />}
                tone="violet"
                active={isActive("/git-projects")}
              />
              <NavItem
                href="/git-projects/issues"
                label="Issues"
                icon={<CircleDot className="h-4 w-4" />}
                tone="amber"
                active={isActive("/git-projects/issues")}
              />
              <NavItem
                href="/tags"
                label="Tags"
                icon={<Tags className="h-4 w-4" />}
                tone="cyan"
                active={isActive("/tags")}
              />
              <NavItem
                href="/approvals"
                label="Approvals"
                icon={<CheckCircle2 className="h-4 w-4" />}
                tone="emerald"
                active={isActive("/approvals")}
              />
              {isAdmin ? (
                <NavItem
                  href="/custom-fields"
                  label="Custom fields"
                  icon={<Settings className="h-4 w-4" />}
                  tone="rose"
                  active={isActive("/custom-fields")}
                />
              ) : null}
            </div>
          </div>

          <div>
            <p className={sectionHeaderClass}>AI Operations</p>
            <div className="mt-2 space-y-1.5">
              <NavItem
                href="/claude-code"
                label="Claude Code"
                icon={<TerminalSquare className="h-4 w-4" />}
                tone="cyan"
                active={isActive("/claude-code")}
              />
              {isAdmin ? (
                <NavItem
                  href="/agents"
                  label="Agents"
                  icon={<Bot className="h-4 w-4" />}
                  tone="violet"
                  active={isActive("/agents")}
                />
              ) : null}
              {isAdmin ? (
                <NavItem
                  href="/gateways"
                  label="Gateways"
                  icon={<Network className="h-4 w-4" />}
                  tone="emerald"
                  active={isActive("/gateways")}
                />
              ) : null}
              <NavItem
                href="/settings/ai-providers"
                label="AI Providers"
                icon={<KeyRound className="h-4 w-4" />}
                tone="amber"
                active={isActive("/settings/ai-providers")}
              />
            </div>
          </div>

          {isAdmin ? (
            <div>
              <p className={sectionHeaderClass}>Skills</p>
              <div className="mt-2 space-y-1.5">
                <NavItem
                  href="/skills/marketplace"
                  label="Marketplace"
                  icon={<Store className="h-4 w-4" />}
                  tone="violet"
                  active={isActive("/skills/marketplace")}
                />
                <NavItem
                  href="/skills/packs"
                  label="Packs"
                  icon={<Boxes className="h-4 w-4" />}
                  tone="cyan"
                  active={isActive("/skills/packs")}
                />
              </div>
            </div>
          ) : null}

          <div>
            <p className={sectionHeaderClass}>Administration</p>
            <div className="mt-2 space-y-1.5">
              <NavItem
                href="/organization"
                label="Organization"
                icon={<Building2 className="h-4 w-4" />}
                tone="blue"
                active={isActive("/organization")}
              />
              <NavItem
                href="/settings"
                label="Settings"
                icon={<Settings className="h-4 w-4" />}
                tone="amber"
                active={isActive("/settings")}
              />
            </div>
          </div>
        </nav>
      </div>
      <div className="border-t border-[color:var(--border)] bg-[color:var(--surface)]/70 p-4">
        <div className="flex items-center gap-2 text-xs font-medium text-[color:var(--text-muted)]">
          <span
            className={cn(
              "h-2.5 w-2.5 rounded-full shadow-[0_0_18px_currentColor]",
              systemStatus === "operational" && "bg-emerald-500 text-emerald-500",
              systemStatus === "degraded" && "bg-rose-500 text-rose-500",
              systemStatus === "unknown" &&
                "bg-[color:var(--text-quiet)] text-[color:var(--text-quiet)]",
            )}
          />
          {statusLabel}
        </div>
      </div>
    </aside>
  );
}
