"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  Bell,
  Bot,
  Boxes,
  Brain,
  ChevronLeft,
  ChevronUp,
  Clock3,
  Database,
  HelpCircle,
  Wrench,
  Home,
  LogOut,
  PlayCircle,
  Video,
} from "lucide-react";
import { useAuth } from "@/components/auth/AuthProvider";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ThemeModeSelector } from "./ThemeToggle";

type SidebarProps = {
  collapsed: boolean;
  onToggle: () => void;
};

type NavItem = {
  href: string;
  label: string;
  icon: React.ComponentType<{ size?: number; className?: string }>;
};

const componentSubItems: NavItem[] = [
  { href: "/components/models", label: "模型资源", icon: Brain },
  { href: "/components/knowledge", label: "知识库", icon: Database },
  { href: "/components/tools", label: "工具资源", icon: Wrench },
];

const monitorSubItems: NavItem[] = [
  { href: "/history", label: "历史记录", icon: Clock3 },
  { href: "/dashboard", label: "数据看板", icon: Database },
];

export function Sidebar({ collapsed, onToggle }: SidebarProps) {
  const pathname = usePathname();
  const router = useRouter();
  const { user, logout } = useAuth();

  // 精确匹配或前缀匹配(带 / 边界),让 /assistants/xxx 也高亮"创建助手"
  const isActive = (href: string) =>
    pathname === href || pathname.startsWith(`${href}/`);

  const componentActive = componentSubItems.some((item) => isActive(item.href));
  const monitorActive = monitorSubItems.some((item) => isActive(item.href));

  async function handleLogout() {
    await logout();
    router.replace("/login");
  }

  return (
    <aside
      className={[
        "flex shrink-0 flex-col overflow-hidden border-r border-sidebar-border bg-sidebar transition-[width] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-[width]",
        collapsed ? "w-[76px]" : "w-[252px]",
      ].join(" ")}
    >
      <div className="shrink-0 flex h-16 items-center gap-3 border-b border-sidebar-border px-5 transition-[padding] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]">
        <div
          className="relative flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl text-on-primary shadow-sm"
          style={{
            backgroundColor: "var(--primary)",
            backgroundImage:
              "radial-gradient(circle at 30% 20%, color-mix(in srgb, var(--gradient-sky) 70%, transparent), transparent 60%), radial-gradient(circle at 80% 90%, color-mix(in srgb, var(--gradient-lavender) 65%, transparent), transparent 55%)",
          }}
        >
          <Video size={22} style={{ color: "var(--primary-foreground)" }} />
        </div>

        <div
          className={[
            "min-w-0 overflow-hidden transition-all duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]",
            collapsed ? "w-0 opacity-0 -translate-x-2" : "w-[140px] opacity-100 translate-x-0",
          ].join(" ")}
        >
          <div className="truncate font-display text-base text-foreground">
            AI 视频助手
          </div>
        </div>
      </div>

      <nav className="scrollbar-subtle min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-3 py-5 pr-2">
        <div className="space-y-1">
          <NavButton
            active={pathname === "/"}
            collapsed={collapsed}
            icon={Home}
            label="首页"
            href="/"
          />
          <div className="pt-2">
            <NavButton
              active={isActive("/assistants")}
              collapsed={collapsed}
              icon={Bot}
              label="创建助手"
              href="/assistants"
            />
          </div>

          <div className="pt-2">
            {collapsed ? (
              <div
                className="flex h-8 items-center justify-center"
                aria-hidden="true"
                title="组件库"
              >
                <span className="h-px w-6 rounded-full bg-hairline-strong" />
              </div>
            ) : (
              <div
                className={[
                  "flex h-11 w-full items-center gap-3 rounded-full px-3 text-sm",
                  componentActive ? "text-foreground" : "text-muted-foreground",
                ].join(" ")}
              >
                <Boxes size={18} />
                <span className="font-medium">组件库</span>
              </div>
            )}

            <div
              className={[
                "mt-1 space-y-1 transition-[padding] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]",
                collapsed ? "pl-0" : "pl-5",
              ].join(" ")}
            >
              {componentSubItems.map((item) => (
                <NavButton
                  key={item.href}
                  active={isActive(item.href)}
                  collapsed={collapsed}
                  icon={item.icon}
                  label={item.label}
                  href={item.href}
                  small
                />
              ))}
            </div>
          </div>


          <div className="pt-2">
          {collapsed ? (
              <div
                className="flex h-8 items-center justify-center"
                aria-hidden="true"
                title="监控观察"
              >
                <span className="h-px w-6 rounded-full bg-hairline-strong" />
              </div>
            ) : (
              <div
                className={[
                  "flex h-11 w-full items-center gap-3 rounded-full px-3 text-sm",
                  monitorActive ? "text-foreground" : "text-muted-foreground",
                ].join(" ")}
              >
                <Boxes size={18} />
                <span className="font-medium">监控观察</span>
              </div>
            )}

            <div
              className={[
                "mt-1 space-y-1 transition-[padding] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]",
                collapsed ? "pl-0" : "pl-5",
              ].join(" ")}
            >
            {monitorSubItems.map((item) => (
              <NavButton
                key={item.href}
                active={isActive(item.href)}
                collapsed={collapsed}
                icon={item.icon}
                label={item.label}
                href={item.href}
              />
            ))}
            </div>
          </div>

          <div className="pt-2">
            <NavButton
              active={isActive("/test")}
              collapsed={collapsed}
              icon={PlayCircle}
              label="测试助手"
              href="/test"
            />
          </div>

        </div>
      </nav>

      <div className="shrink-0 space-y-2 border-t border-sidebar-border bg-sidebar p-3 shadow-[0_-12px_24px_rgba(0,0,0,0.12)]">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button
              type="button"
              title={collapsed ? `用户菜单 · ${user?.displayName ?? "超级管理员"}` : undefined}
              className={[
                "group relative flex h-12 w-full items-center overflow-hidden rounded-xl border border-transparent text-left text-muted-foreground transition-[background-color,color,border-color,box-shadow,transform] duration-200 hover:border-sidebar-border hover:bg-sidebar-accent/60 hover:text-foreground hover:shadow-sm active:scale-[0.98] data-[state=open]:border-sidebar-border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground",
                collapsed ? "justify-center gap-0 px-0" : "gap-3 px-2.5",
              ].join(" ")}
            >
              <span className="relative shrink-0">
                <span
                  className="flex h-8 w-8 items-center justify-center rounded-full text-xs font-medium text-on-primary shadow-sm transition-transform duration-200 group-hover:scale-105"
                  style={{
                    backgroundColor: "var(--primary)",
                    backgroundImage:
                      "radial-gradient(circle at 30% 20%, color-mix(in srgb, var(--gradient-sky) 70%, transparent), transparent 60%), radial-gradient(circle at 80% 90%, color-mix(in srgb, var(--gradient-lavender) 65%, transparent), transparent 55%)",
                  }}
                >
                  <span style={{ color: "var(--primary-foreground)" }}>管</span>
                </span>
                <span
                  className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-sidebar"
                  style={{ backgroundColor: "var(--success)" }}
                />
              </span>

              <span
                className={[
                  "min-w-0 overflow-hidden transition-all duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]",
                  collapsed ? "w-0 flex-none opacity-0 -translate-x-2" : "flex-1 opacity-100 translate-x-0",
                ].join(" ")}
              >
                <span className="block truncate text-sm font-medium text-foreground">
                  {user?.displayName ?? "超级管理员"}
                </span>
              </span>

              <ChevronUp
                size={16}
                className={[
                  "shrink-0 transition-[opacity,transform] duration-200 group-data-[state=open]:rotate-180",
                  collapsed ? "w-0 opacity-0" : "opacity-70",
                ].join(" ")}
              />
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            side="top"
            align="start"
            sideOffset={8}
            className={[
              "w-[228px] rounded-2xl border border-hairline bg-popover p-1.5 shadow-lg",
              collapsed ? "min-w-[228px]" : "",
            ].join(" ")}
          >
            <ThemeModeSelector />
            <DropdownMenuSeparator />
            <DropdownMenuItem className="h-10 rounded-xl px-3 font-normal">
              <HelpCircle size={16} />
              帮助
            </DropdownMenuItem>
            <DropdownMenuItem className="h-10 rounded-xl px-3 font-normal">
              <Bell size={16} />
              消息提示
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              variant="destructive"
              className="h-10 rounded-xl px-3 font-normal"
              onSelect={() => void handleLogout()}
            >
              <LogOut size={16} />
              退出登录
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>

        {/* 收起 / 展开侧栏 */}
        <button
          onClick={onToggle}
          title={collapsed ? "展开侧栏" : "收起侧栏"}
          className={[
            "group flex h-10 w-full items-center overflow-hidden rounded-full border border-hairline-strong text-sm text-muted-foreground transition-[background-color,color,border-color,transform] duration-200 hover:bg-surface-strong hover:text-foreground active:scale-[0.98]",
            collapsed ? "justify-center gap-0 px-0" : "justify-between gap-2 px-3.5",
          ].join(" ")}
        >
          <span
            className={[
              "min-w-0 truncate transition-all duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]",
              collapsed ? "w-0 opacity-0 -translate-x-2" : "opacity-100 translate-x-0",
            ].join(" ")}
          >
            收起侧栏
          </span>
          <ChevronLeft
            size={18}
            className={[
              "shrink-0 transition-transform duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] group-hover:scale-110",
              collapsed ? "rotate-180" : "rotate-0",
            ].join(" ")}
          />
        </button>
      </div>
    </aside>
  );
}

function NavButton({
  active,
  collapsed,
  icon: Icon,
  label,
  href,
  small = false,
}: {
  active: boolean;
  collapsed: boolean;
  icon: React.ComponentType<{ size?: number; className?: string }>;
  label: string;
  href: string;
  small?: boolean;
}) {
  return (
    <Link
      href={href}
      title={collapsed ? label : undefined}
      className={[
        "group mt-1 flex w-full items-center overflow-hidden rounded-full text-sm transition-[background-color,color,transform] duration-200 active:scale-[0.98]",
        small ? "h-10" : "h-11",
        active
          ? "bg-sidebar-accent text-sidebar-accent-foreground font-medium"
          : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
        collapsed ? "justify-center gap-0 px-0" : "gap-3 px-3 hover:translate-x-0.5",
      ].join(" ")}
    >
      <Icon
        size={small ? 16 : 18}
        className="shrink-0 transition-transform duration-200 group-hover:scale-105"
      />
      <span
        className={[
          "min-w-0 truncate transition-all duration-300 ease-[cubic-bezier(0.22,1,0.36,1)]",
          collapsed ? "w-0 opacity-0 -translate-x-2" : "w-[150px] opacity-100 translate-x-0",
        ].join(" ")}
      >
        {label}
      </span>
    </Link>
  );
}
