"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bell, ChevronDown, ChevronRight, Sprout } from "lucide-react";
import { brapiNavSections, brapiTopNav, getBrapiBreadcrumbs } from "@/components/brapi/navigation";
import { BrapiUserMenu } from "@/components/brapi/BrapiUserMenu";
import { ThemeToggle } from "@/components/brapi/ThemeToggle";
import { cn } from "@/lib/utils";

export function BrapiSidebar() {
  const pathname = usePathname();
  const [expandedSections, setExpandedSections] = useState<Set<string>>(
    new Set(brapiNavSections.map((section) => section.id))
  );

  const toggleSection = (id: string) => {
    setExpandedSections((current) => {
      const next = new Set(current);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  return (
    <aside className="hidden h-screen w-64 shrink-0 flex-col border-r border-slate-200 bg-white lg:flex dark:border-slate-800 dark:bg-slate-950">
      <div className="border-b border-slate-100 px-4 py-4 dark:border-slate-800">
        <Link href="/dashboard" className="flex items-center gap-2.5">
          <div className="grid h-8 w-8 place-items-center rounded-lg bg-gradient-to-br from-green-500 to-emerald-600">
            <Sprout className="h-[18px] w-[18px] text-white" />
          </div>
          <div>
            <p className="text-sm font-semibold leading-tight text-slate-900 dark:text-slate-50">BrAPI 数据管理</p>
            <p className="text-[11px] text-slate-400">Breeding Data Platform</p>
          </div>
        </Link>
      </div>

      <nav className="flex-1 overflow-y-auto px-2 py-3">
        {brapiTopNav.map((item) => {
          const Icon = item.icon;
          const active = pathname === item.href || (item.href !== "/" && pathname.startsWith(`${item.href}/`));
          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "mb-1 flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-colors",
                active ? "bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-950" : "text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-900"
              )}
            >
              <Icon className="h-4 w-4 shrink-0" />
              <span>概览 Dashboard</span>
            </Link>
          );
        })}

        {brapiNavSections.map((section) => {
          const expanded = expandedSections.has(section.id);
          const SectionIcon = section.icon;
          const isSectionActive = section.groups.some((group) => group.items.some((item) => pathname === item.href || pathname.startsWith(`${item.href}/`)));

          return (
            <div key={section.id} className="mb-1">
              <button
                type="button"
                onClick={() => toggleSection(section.id)}
                className={cn(
                  "flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-colors hover:bg-slate-50 dark:hover:bg-slate-900",
                  isSectionActive && !expanded && "bg-slate-100 dark:bg-slate-900"
                )}
              >
                <SectionIcon className={cn("h-4 w-4 shrink-0", section.accentClass)} />
                <span className="flex-1 text-left text-[13px] text-slate-700 dark:text-slate-200">{section.title}</span>
                {expanded ? <ChevronDown className="h-3.5 w-3.5 text-slate-400" /> : <ChevronRight className="h-3.5 w-3.5 text-slate-400" />}
              </button>

              {expanded ? (
                <div className="ml-3 mt-0.5">
                  {section.groups.map((group) => (
                    <div key={group.title} className="mb-1">
                      <p className="px-3 py-1 text-[10px] uppercase tracking-wider text-slate-400">{group.title}</p>
                      {group.items.map((item) => {
                        const Icon = item.icon;
                        const active = pathname === item.href || pathname.startsWith(`${item.href}/`);
                        return (
                          <Link
                            key={item.href}
                            href={item.href}
                            className={cn(
                              "mb-0.5 flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors",
                              active ? section.activeClass : "text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-900"
                            )}
                          >
                            <Icon className="h-3.5 w-3.5 shrink-0" />
                            <span className="truncate">{item.title}</span>
                          </Link>
                        );
                      })}
                    </div>
                  ))}
                </div>
              ) : null}
            </div>
          );
        })}
      </nav>

      <div className="border-t border-slate-100 px-4 py-3 dark:border-slate-800">
        <p className="text-[11px] text-slate-400">BrAPI v2 Standard</p>
      </div>
    </aside>
  );
}

export function BrapiTopbar() {
  const pathname = usePathname();
  const breadcrumbs = useMemo(() => getBrapiBreadcrumbs(pathname), [pathname]);

  return (
    <header className="sticky top-0 z-20 flex h-14 items-center justify-between border-b border-slate-200 bg-white/90 px-6 backdrop-blur dark:border-slate-800 dark:bg-slate-950/90">
      <div className="flex items-center gap-2 text-sm">
        {breadcrumbs.map((item, index) => (
          <span key={`${item}-${index}`} className={cn(index === breadcrumbs.length - 1 ? "font-medium text-slate-900 dark:text-slate-50" : "text-slate-400")}>
            {item}{index < breadcrumbs.length - 1 ? <span className="mx-2 text-slate-300">/</span> : null}
          </span>
        ))}
      </div>
      <div className="flex items-center gap-3">
        <button className="relative rounded-lg p-2 text-slate-500 transition hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-900" type="button">
          <Bell className="h-4 w-4" />
          <span className="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-green-500" />
        </button>
        <ThemeToggle />
        <BrapiUserMenu />
      </div>
    </header>
  );
}

