import { Link, Outlet, useLocation, useNavigate, useParams } from "react-router";
import {
  Bell,
  BookOpen,
  Bot,
  ChevronDown,
  Clapperboard,
  Coins,
  FileText,
  Film,
  FolderOpen,
  Globe,
  Headphones,
  HelpCircle,
  Image as ImageIcon,
  LayoutDashboard,
  LogOut,
  Menu,
  Search,
  Settings,
  ShieldCheck,
  Sparkles,
  Users,
  Video,
  Wand2,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useAuthStore } from "../../stores/authStore";
import { useBalance } from "../../hooks/useUsage";
import { useProject } from "../../hooks/useProjects";
import { useTeamGroups } from "../../hooks/useTeam";
import { useAuth } from "../../hooks/useAuth";

const consoleLinks = ["企业", "工具", "费用", "支持", "备案", "文档"];

export function Layout() {
  const location = useLocation();
  const params = useParams();
  const navigate = useNavigate();
  const [showNotifications, setShowNotifications] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [currentGroupId, setCurrentGroupId] = useState<number | "">("");
  const userMenuRef = useRef<HTMLDivElement>(null);

  const user = useAuthStore((state) => state.user);
  const { logout } = useAuth();
  const { data: balance } = useBalance();
  const { data: teamGroups = [] } = useTeamGroups();

  const projectId = params.projectId;
  const isProjectRoute = projectId !== undefined;
  const { data: currentProject } = useProject(projectId ?? "");

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (userMenuRef.current && !userMenuRef.current.contains(e.target as Node)) {
        setShowUserMenu(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const getActiveSection = () => {
    const path = location.pathname;
    if (path.includes("/agent")) return "agent";
    if (path.includes("/storyboard")) return "storyboard";
    if (path.includes("/video")) return "video";
    if (path.includes("/characters") || path.includes("/scenes") || path.includes("/props") || path.includes("/settings")) {
      return "settings";
    }
    return "script";
  };

  const projectSections = [
    { id: "agent", label: "Agent制作", icon: Bot, path: `/project/${projectId}/agent` },
    { id: "script", label: "剧本", icon: FileText, path: `/project/${projectId}` },
    { id: "settings", label: "设定", icon: Wand2, path: `/project/${projectId}/characters` },
    { id: "storyboard", label: "分镜", icon: Clapperboard, path: `/project/${projectId}/storyboard` },
    { id: "video", label: "视频", icon: Video, path: `/project/${projectId}/video` },
  ];

  const notifications = [
    {
      id: 1,
      title: "项目《重生之豪门千金》第3集分镜待审核",
      time: "5分钟前",
      path: projectId ? `/project/${projectId}/storyboard` : "/",
    },
    { id: 2, title: "系统更新：新增AI水印功能", time: "1小时前", path: "/settings" },
    {
      id: 3,
      title: "张三提交的角色设定已通过审核",
      time: "2小时前",
      path: projectId ? `/project/${projectId}/characters` : "/",
    },
  ];

  const primaryMenu = [
    { label: "剧本生短剧", icon: Sparkles, path: "/new-project", active: location.pathname === "/new-project" },
    { label: "项目", icon: FolderOpen, path: "/", active: location.pathname === "/" },
    { label: "资产", icon: ImageIcon, path: "/assets/character", active: location.pathname.startsWith("/assets") },
  ];

  const enterpriseMenu = [
    { label: "团队管理", icon: Users, path: "/team" },
    { label: "用量统计", icon: LayoutDashboard, path: "/usage" },
    { label: "模型配置", icon: Settings, path: "/models" },
    { label: "AI 生成水印设置", icon: ShieldCheck, path: "/settings" },
  ];

  return (
    <div className="h-screen w-full max-w-full overflow-hidden bg-[#f6f7fb] text-[#0f172a]">
      <header className="relative z-40 flex h-12 w-full max-w-full min-w-0 items-center overflow-visible border-b border-[#dfe3ee] bg-white shadow-[0_1px_5px_rgba(15,23,42,0.06)]">
        <div className="flex h-full w-auto flex-shrink-0 items-center gap-3 px-4 md:w-[200px]">
          <button className="flex h-8 w-8 items-center justify-center rounded-md hover:bg-[#f1f4fb]" aria-label="展开产品服务">
            <Menu className="h-5 w-5 text-[#1f2937]" />
          </button>
          <Link to="/" className="flex items-center gap-2">
            <div className="flex h-7 w-7 items-center justify-center rounded-md bg-gradient-to-br from-[#0073ff] to-[#7b2cff]">
              <Film className="h-4 w-4 text-white" />
            </div>
            <span className="text-base font-semibold tracking-normal text-[#7a5cf6]">Dramix.ai</span>
          </Link>
        </div>

        <Link
          to="/"
          className="mr-3 hidden h-8 flex-shrink-0 items-center gap-1.5 whitespace-nowrap rounded bg-[#eef3ff] px-3 text-sm font-medium text-[#1664ff] sm:flex md:mr-6"
        >
          <LayoutDashboard className="h-4 w-4" />
          总览
        </Link>

        <div className="relative hidden w-[min(28vw,420px)] min-w-[220px] flex-shrink lg:block">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#8a94a6]" />
          <input
            className="h-8 w-full rounded border border-[#d6dbe7] bg-white pl-9 pr-3 text-sm outline-none transition focus:border-[#1664ff] focus:ring-2 focus:ring-[#1664ff]/10"
            placeholder="搜索产品或文档"
          />
        </div>

        <div className="ml-auto flex h-full flex-shrink-0 items-center gap-1 pr-4 text-sm text-[#202b3d]">
          <nav className="hidden h-full max-w-[56vw] flex-shrink items-center justify-end gap-1 overflow-hidden xl:flex">
            {consoleLinks.map((item) => (
              <button key={item} className="flex h-9 flex-shrink-0 items-center gap-1 whitespace-nowrap rounded px-2.5 hover:bg-[#f3f6fb]">
                {item}
                {["企业", "工具", "费用", "支持"].includes(item) && <ChevronDown className="h-3.5 w-3.5" />}
              </button>
            ))}
          </nav>
          <div className="relative">
            <button
              onClick={() => setShowNotifications((show) => !show)}
              className="relative flex h-9 w-9 flex-shrink-0 items-center justify-center rounded hover:bg-[#f3f6fb]"
              aria-label="通知"
            >
              <Bell className="h-4 w-4" />
              <span className="absolute right-1.5 top-1 rounded-full bg-[#f43f5e] px-1 text-[10px] leading-4 text-white">9</span>
            </button>
            {showNotifications && (
              <div className="absolute right-0 top-11 z-50 w-80 overflow-hidden rounded-lg border border-[#dfe3ee] bg-white shadow-xl">
                <div className="border-b border-[#edf0f6] px-4 py-3 text-sm font-medium text-[#111827]">通知</div>
                {notifications.map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => {
                      setShowNotifications(false);
                      navigate(item.path);
                    }}
                    className="block w-full border-b border-[#f1f3f8] px-4 py-3 text-left transition hover:bg-[#f6f9ff] focus:bg-[#f6f9ff] focus:outline-none last:border-b-0"
                  >
                    <div className="text-sm text-[#1f2937]">{item.title}</div>
                    <div className="mt-1 text-xs text-[#8a94a6]">{item.time}</div>
                  </button>
                ))}
              </div>
            )}
          </div>
          <button className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded hover:bg-[#f3f6fb]" aria-label="语言">
            <Globe className="h-4 w-4 text-[#1664ff]" />
          </button>
          <div className="relative" ref={userMenuRef}>
            <button
              onClick={() => setShowUserMenu((show) => !show)}
              className="flex h-9 items-center gap-2 rounded-full bg-[#eef4ff] px-2.5 text-sm font-medium text-[#2662d9]"
            >
              {user?.username?.[0]?.toUpperCase() ?? "U"}
              <ChevronDown className="h-3.5 w-3.5" />
            </button>
            {showUserMenu && (
              <div className="absolute right-0 top-11 z-50 w-52 overflow-hidden rounded-lg border border-[#dfe3ee] bg-white shadow-xl">
                <div className="border-b border-[#edf0f6] px-4 py-3 text-sm">
                  <div className="font-medium text-[#111827]">{user?.username ?? "用户"}</div>
                  <div className="mt-0.5 text-xs text-[#7b8496]">Dramix 控制台</div>
                </div>
                <button
                  onClick={() => {
                    logout();
                    setShowUserMenu(false);
                  }}
                  className="flex w-full items-center gap-2 px-4 py-2.5 text-left text-sm text-[#d92d20] hover:bg-[#fff1f0]"
                >
                  <LogOut className="h-4 w-4" />
                  退出登录
                </button>
              </div>
            )}
          </div>
        </div>
      </header>

      <div className="flex h-[calc(100vh-48px)] w-full min-w-0 overflow-hidden">
        {!isProjectRoute && (
          <aside className="hidden w-[200px] flex-col border-r border-[#dfe3ee] bg-[#fbfcff] md:flex">
            <div className="px-4 pb-5 pt-7">
              <div className="mb-6 flex items-center gap-3">
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-[#e8eaff] text-[#5a50ff]">
                  <Sparkles className="h-4 w-4" />
                </div>
                <div className="flex items-center gap-1.5">
                  <span className="text-lg font-semibold text-[#111827]">Dramix</span>
                  <span className="rounded bg-[#eef1f7] px-1.5 py-0.5 text-[10px] text-[#6b7280]">Beta</span>
                </div>
              </div>

              <div className="relative">
                <select
                  value={currentGroupId}
                  onChange={(e) => setCurrentGroupId(Number(e.target.value) || "")}
                  className="h-9 w-full appearance-none rounded-md border border-[#dfe3ee] bg-white px-9 pr-8 text-sm text-[#1f2937] outline-none focus:border-[#1664ff]"
                >
                  <option value="">默认团队</option>
                  {teamGroups.map((group) => (
                    <option key={group.id} value={group.id}>
                      {group.name}
                    </option>
                  ))}
                </select>
                <Users className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#6f65ff]" />
                <ChevronDown className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#7b8496]" />
              </div>
            </div>

            <nav className="flex-1 overflow-auto px-4 text-sm">
              <div className="mb-3 text-xs text-[#667085]">创作</div>
              {primaryMenu.slice(0, 1).map((item) => (
                <Link
                  key={item.label}
                  to={item.path}
                  className={`mb-5 flex h-10 items-center gap-3 rounded-lg px-3 font-medium transition ${
                    item.active ? "bg-[#eceeff] text-[#5547ff]" : "text-[#344054] hover:bg-[#f0f3fa]"
                  }`}
                >
                  <item.icon className="h-4 w-4" />
                  {item.label}
                </Link>
              ))}

              <div className="mb-3 text-xs text-[#667085]">我的</div>
              {primaryMenu.slice(1).map((item) => (
                <Link
                  key={item.label}
                  to={item.path}
                  className={`mb-1 flex h-10 items-center gap-3 rounded-lg px-3 transition ${
                    item.active ? "bg-[#eceeff] text-[#5547ff]" : "text-[#344054] hover:bg-[#f0f3fa]"
                  }`}
                >
                  <item.icon className="h-4 w-4" />
                  {item.label}
                </Link>
              ))}

              <div className="my-5 h-px bg-[#e5e8f0]" />
              <div className="mb-3 text-xs text-[#667085]">企业配置</div>
              {enterpriseMenu.map((item) => {
                const active = location.pathname === item.path;
                return (
                  <Link
                    key={item.label}
                    to={item.path}
                    className={`mb-1 flex h-10 items-center gap-3 rounded-lg px-3 transition ${
                      active ? "bg-[#eceeff] text-[#5547ff]" : "text-[#344054] hover:bg-[#f0f3fa]"
                    }`}
                  >
                    <item.icon className="h-4 w-4" />
                    {item.label}
                  </Link>
                );
              })}
            </nav>

            <button
              onClick={() => navigate("/usage")}
              className="m-3 flex h-10 items-center justify-between rounded-lg border border-[#dfe3ee] bg-white px-3 text-sm hover:border-[#b7c4dc]"
            >
              <span className="flex items-center gap-2 font-medium text-[#5547ff]">
                <Coins className="h-4 w-4" />
                {Number(balance?.balance ?? 0).toLocaleString()}
              </span>
              <span className="flex items-center gap-1 text-[#5547ff]">
                购买
                <ChevronDown className="h-3.5 w-3.5 -rotate-90" />
              </span>
            </button>
          </aside>
        )}

        <section className="relative flex min-w-0 flex-1 flex-col overflow-hidden">
          {isProjectRoute && (
            <div className="flex h-16 items-center border-b border-[#e5e8f0] bg-[#fbfcff] px-5">
              <div className="flex min-w-[310px] items-center gap-3">
                <button
                  type="button"
                  onClick={() => navigate("/")}
                  className="flex h-7 w-7 items-center justify-center rounded-md text-[#111827] hover:bg-[#edf1f8]"
                  aria-label="返回项目列表"
                >
                  <ChevronDown className="h-4 w-4 rotate-90" />
                </button>
                <div className="min-w-0">
                  <div className="flex items-center gap-1.5">
                    <span className="max-w-[270px] truncate text-sm font-semibold text-[#111827]">
                      {currentProject?.name ?? projectId}
                    </span>
                    <button className="text-[#98a2b3] hover:text-[#6f55f2]" aria-label="编辑项目名">
                      <FileText className="h-3.5 w-3.5" />
                    </button>
                  </div>
                  <div className="mt-1 flex items-center gap-3 text-[11px] text-[#667085]">
                    <span>9:16</span>
                    <span>720</span>
                    <span>写实电影感</span>
                  </div>
                </div>
              </div>

              <div className="mx-auto hidden items-center gap-5 xl:flex">
                {projectSections.filter((section) => section.id !== "agent").map((section, index, arr) => {
                  const Icon = section.icon;
                  const active = getActiveSection() === section.id;
                  return (
                    <div key={section.id} className="flex items-center gap-5">
                      <button
                        onClick={() => navigate(section.path)}
                        className={`flex h-12 min-w-[96px] flex-col items-center justify-center gap-1 rounded-full border px-6 text-xs transition ${
                          active
                            ? "border-[#7657ff] bg-white text-[#7657ff] shadow-[0_6px_18px_rgba(118,87,255,0.18)]"
                            : "border-[#e2e6ef] bg-white text-[#111827] hover:border-[#b8c1d4]"
                        }`}
                      >
                        <Icon className="h-4 w-4" />
                        {section.label}
                      </button>
                      {index < arr.length - 1 && <span className="h-px w-8 bg-[#d9dee9]" />}
                    </div>
                  );
                })}
              </div>

              <div className="ml-auto flex min-w-[260px] items-center justify-end gap-3">
                <button className="text-xs text-[#667085] hover:text-[#6f55f2]">优化建议</button>
                <button
                  onClick={() => navigate("/usage")}
                  className="flex h-8 items-center gap-1.5 rounded-md border border-[#d9d2ff] bg-[#f6f2ff] px-3 text-xs font-semibold text-[#6f55f2]"
                >
                  <Sparkles className="h-3.5 w-3.5" />
                  {Number(balance?.balance ?? 7492538).toLocaleString()}
                </button>
              </div>
            </div>
          )}

          <main className="min-h-0 w-full min-w-0 flex-1 overflow-auto overflow-x-hidden bg-[#f6f7fb]">
            <Outlet />
          </main>

          <div className="pointer-events-none fixed bottom-7 right-3 z-30 flex flex-col gap-3">
            {[Sparkles, Headphones, BookOpen, HelpCircle].map((Icon, index) => (
              <button
                key={index}
                className="pointer-events-auto flex h-12 w-12 items-center justify-center rounded-full bg-white text-[#344054] shadow-[0_6px_20px_rgba(15,23,42,0.16)] transition hover:text-[#5547ff]"
                aria-label="快捷入口"
              >
                <Icon className="h-5 w-5" />
              </button>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}
