"use client";

import * as React from "react";
import { usePathname, useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { SideNav, NavGroup, NavItem } from "@/components/layout/side-nav";
import {
  LayoutDashboard,
  FolderKanban,
  Search,
  Target,
  Sparkles,
  Share2,
  BarChart3,
  BookOpen,
  Zap,
  Bot,
  Users,
  Settings,
} from "lucide-react";

// ─── Nav Config ───────────────────────────────────────────────────────────────

const NAV_GROUPS: NavGroup[] = [
  {
    id: "overview",
    title: "概览",
    items: [
      {
        id: "dashboard",
        label: "Dashboard",
        href: "/dashboard",
        icon: <LayoutDashboard className="h-4 w-4" />,
      },
    ],
  },
  {
    id: "main",
    title: "核心功能",
    items: [
      {
        id: "content",
        label: "内容工坊",
        href: "/dashboard/content",
        icon: <Sparkles className="h-4 w-4" />,
      },
      {
        id: "distribution",
        label: "分发中心",
        href: "/dashboard/distribution",
        icon: <Share2 className="h-4 w-4" />,
      },
      {
        id: "analytics",
        label: "数据监测",
        href: "/dashboard/analytics",
        icon: <BarChart3 className="h-4 w-4" />,
      },
      {
        id: "knowledge",
        label: "知识库",
        href: "/dashboard/knowledge",
        icon: <BookOpen className="h-4 w-4" />,
      },
    ],
  },
  {
    id: "lifecycle",
    title: "生命周期",
    items: [
      {
        id: "lifecycle-new",
        label: "快速开始",
        href: "/dashboard/lifecycle/new",
        icon: <Zap className="h-4 w-4" />,
      },
      {
        id: "lifecycle",
        label: "项目管理",
        href: "/dashboard/lifecycle",
        icon: <FolderKanban className="h-4 w-4" />,
      },
      {
        id: "diagnosis",
        label: "诊断分析",
        href: "/dashboard/diagnosis",
        icon: <Search className="h-4 w-4" />,
      },
      {
        id: "strategy",
        label: "策略制定",
        href: "/dashboard/strategy",
        icon: <Target className="h-4 w-4" />,
      },
    ],
  },
  {
    id: "tools",
    title: "工具",
    items: [
      {
        id: "agents",
        label: "AI Agents",
        href: "/dashboard/agents",
        icon: <Bot className="h-4 w-4" />,
      },
    ],
  },
  {
    id: "manage",
    title: "管理",
    items: [
      {
        id: "clients",
        label: "客户管理",
        href: "/dashboard/clients",
        icon: <Users className="h-4 w-4" />,
      },
      {
        id: "settings",
        label: "设置",
        href: "/dashboard/settings",
        icon: <Settings className="h-4 w-4" />,
      },
    ],
  },
];

// Flatten all items for activeId lookup
const ALL_NAV_ITEMS: NavItem[] = NAV_GROUPS.flatMap((g) => g.items);

// ─── Layout ───────────────────────────────────────────────────────────────────

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { data: session, status } = useSession();
  const pathname = usePathname();
  const router = useRouter();

  // Redirect to login if unauthenticated
  React.useEffect(() => {
    if (status === "unauthenticated") {
      router.replace("/login");
    }
  }, [status, router]);

  // Responsive: collapse on mobile by default
  const [collapsed, setCollapsed] = React.useState(false);
  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 768px)");
    setCollapsed(mq.matches);
    const handler = (e: MediaQueryListEvent) => setCollapsed(e.matches);
    mq.addEventListener("change", handler);
    return () => mq.removeEventListener("change", handler);
  }, []);

  // Compute activeId: match longest href prefix
  const activeId = React.useMemo(() => {
    // Sort by href length descending for longest-prefix match
    const sorted = [...ALL_NAV_ITEMS]
      .filter((item) => item.href)
      .sort((a, b) => (b.href?.length ?? 0) - (a.href?.length ?? 0));
    return sorted.find((item) => item.href && pathname.startsWith(item.href))?.id ?? "dashboard";
  }, [pathname]);

  // Handle nav click: navigate to href
  const handleNavClick = React.useCallback(
    (item: NavItem) => {
      if (item.href) {
        router.push(item.href);
      }
    },
    [router]
  );

  // Build SideNavUser from session
  const sideNavUser = session?.user
    ? {
        name: session.user.name ?? session.user.email ?? "用户",
        email: session.user.email ?? undefined,
        avatar: session.user.image ?? undefined,
      }
    : undefined;

  if (status === "loading") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-geo-bg">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/80" />
      </div>
    );
  }

  if (status === "unauthenticated") {
    return null;
  }

  return (
    <div className="flex min-h-screen bg-geo-bg">
      {/* Fixed SideNav */}
      <aside
        className="fixed inset-y-0 left-0 z-40 flex flex-col"
        style={{ width: collapsed ? 64 : 240 }}
      >
        <SideNav
          groups={NAV_GROUPS}
          activeId={activeId}
          collapsed={collapsed}
          onCollapsedChange={setCollapsed}
          onNavClick={handleNavClick}
          user={sideNavUser}
          className="h-full"
        />
      </aside>

      {/* Main content with left margin matching SideNav width */}
      <main
        className="flex-1 min-h-screen transition-all duration-300"
        style={{ marginLeft: collapsed ? 64 : 240 }}
      >
        <div className="p-6">{children}</div>
      </main>
    </div>
  );
}
