import { Navbar } from "@contentful/f36-navbar";
import {
  MagnifyingGlassIcon,
  QuestionIcon,
  GearSixIcon,
} from "@contentful/f36-icons";
import { useAuth } from "../../contexts/AuthContext";
import { useMenu } from "../../contexts/MenuContext";
import { useNavigate, useLocation } from "react-router-dom";
import { useEffect, useState } from "react";
import type { JeecgMenu } from "../../types/menu";
import SearchModal from "../../components/SearchModal";

export default function Header() {
  const { menus, loading } = useAuth();
  const { activeFirstMenu, setActiveFirstMenu, setActiveSecondMenu } =
    useMenu();
  const navigate = useNavigate();
  const location = useLocation();
  const [isSearchOpen, setIsSearchOpen] = useState(false);

  // 获取顶级菜单（一级菜单）
  const topMenus = menus.filter((menu) => !menu.hidden && !menu.meta?.hideMenu);

  // 根据当前路由自动设置活动菜单
  useEffect(() => {
    const path = location.pathname;
    const segments = path.split("/").filter(Boolean);
    const firstPath = segments[0];

    const matchedMenu = topMenus.find((menu) => {
      const menuPath = menu.path || "";
      const menuSegments = menuPath.split("/").filter(Boolean);
      return menuSegments[0] === firstPath;
    });

    if (matchedMenu && matchedMenu.id !== activeFirstMenu?.id) {
      setActiveFirstMenu(matchedMenu);
      setActiveSecondMenu(null);
    }
  }, [
    location.pathname,
    topMenus,
    activeFirstMenu,
    setActiveFirstMenu,
    setActiveSecondMenu,
  ]);

  // 处理菜单点击
  const handleMenuClick = (menu: JeecgMenu, child?: JeecgMenu) => {
    if (child) {
      // 点击子菜单
      setActiveFirstMenu(menu);
      setActiveSecondMenu(child);
      navigate(child.path || "");
    } else {
      // 点击一级菜单（无子菜单）
      setActiveFirstMenu(menu);
      setActiveSecondMenu(null);
      navigate(menu.path || "");
    }
  };

  // 跳转到权限管理
  const toPermissionPage = () => {
    debugger;
  };

  // 退出登录
  const loginOut = () => {
    navigate('/login')
  }

  if (loading) {
    return <div style={{ padding: "16px" }}>加载中...</div>;
  }

  // 渲染主导航（桌面端）
  const mainNavigation = (
    <>
      {topMenus.map((menu) => {
        const hasChildren = menu.children && menu.children.length > 0;
        const isActive = activeFirstMenu?.id === menu.id;

        if (hasChildren) {
          // 有子菜单的项目
          return (
            <Navbar.Item
              key={menu.id}
              title={menu.meta?.title || menu.name}
              isActive={isActive}
            >
              {menu.children
                ?.filter((child) => !child.hidden && !child.meta?.hideMenu)
                .map((child) => (
                  <Navbar.MenuItem
                    key={child.id}
                    title={child.meta?.title || child.name}
                    onClick={() => handleMenuClick(menu, child)}
                  />
                ))}
            </Navbar.Item>
          );
        } else {
          // 无子菜单的项目
          return (
            <Navbar.Item
              key={menu.id}
              title={menu.meta?.title || menu.name}
              isActive={isActive}
              onClick={() => handleMenuClick(menu)}
            />
          );
        }
      })}
    </>
  );

  // 渲染移动端导航
  const mobileNavigation = (
    <>
      {topMenus.map((menu) => {
        const hasChildren = menu.children && menu.children.length > 0;

        if (hasChildren) {
          // 有子菜单的项目
          return (
            <Navbar.Submenu key={menu.id} title={menu.meta?.title || menu.name}>
              {menu.children
                ?.filter((child) => !child.hidden && !child.meta?.hideMenu)
                .map((child) => (
                  <Navbar.MenuItem
                    key={child.id}
                    title={child.meta?.title || child.name}
                    onClick={() => handleMenuClick(menu, child)}
                  />
                ))}
            </Navbar.Submenu>
          );
        } else {
          // 无子菜单的项目
          return (
            <Navbar.MenuItem
              key={menu.id}
              title={menu.meta?.title || menu.name}
              onClick={() => handleMenuClick(menu)}
            />
          );
        }
      })}
    </>
  );

  // 右侧辅助导航
  const secondaryNavigation = (
    <>
      <Navbar.Item
        label="快速搜索"
        icon={<MagnifyingGlassIcon />}
        onClick={() => setIsSearchOpen(true)}
      />
      <Navbar.Item label="帮助菜单" icon={<QuestionIcon />}>
        <Navbar.MenuItem
          as="a"
          target="_blank"
          rel="noopener noreferrer"
          title="帮助中心"
          href="https://www.contentful.com/help/"
        />
        <Navbar.MenuItem
          as="a"
          target="_blank"
          rel="noopener noreferrer"
          title="开发者文档"
          href="https://www.contentful.com/developers/docs/"
        />
        <Navbar.MenuDivider />
        <Navbar.MenuItem
          as="a"
          target="_blank"
          rel="noopener noreferrer"
          title="获取支持"
          href="https://support.contentful.com"
        />
      </Navbar.Item>
      <Navbar.Item label="设置菜单" icon={<GearSixIcon />}>
        <Navbar.MenuSectionTitle>通用</Navbar.MenuSectionTitle>
        <Navbar.MenuItem title="首页" />
        <Navbar.MenuItem title="API 密钥" />
        <Navbar.MenuSectionTitle>空间</Navbar.MenuSectionTitle>
        <Navbar.MenuItem title="应用" />
        <Navbar.MenuItem title="权限" onClick={toPermissionPage} />
      </Navbar.Item>
    </>
  );

  return (
    <>
      <Navbar
        mainNavigation={mainNavigation}
        mobileNavigation={mobileNavigation}
        // switcher={
        //   <Navbar.Switcher
        //     isAlias={false}
        //     envVariant="master"
        //     space="Content Space"
        //     environment="master"
        //   />
        // }
        secondaryNavigation={secondaryNavigation}
        account={
          <Navbar.Account username="管理员" initials="A" label="账户设置">
            <Navbar.MenuItem title="账户设置" />
            <Navbar.MenuItem title="控制台" />
            <Navbar.MenuDivider />
            <Navbar.MenuItem
              title="外部链接"
              as="a"
              href="https://www.contentful.com"
              target="_blank"
              rel="noopener noreferrer"
            />
            <Navbar.MenuDivider />
            <Navbar.MenuItem title="退出登录" onClick={loginOut} />
          </Navbar.Account>
        }
        aria={{
          labelMainNavigation: "主导航",
          labelSecondaryNavigation: "辅助导航",
          labelAccount: "我的账户",
        }}
      />

      {/* 搜索对话框 */}
      <SearchModal
        isOpen={isSearchOpen}
        onClose={() => setIsSearchOpen(false)}
      />
    </>
  );
}
