import { FC, useCallback, useMemo, useState } from "react";
import style from "./index.module.scss";
import { App, Avatar, Breadcrumb, Button, Popover } from "antd";
import { Header } from "antd/es/layout/layout";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { ResetPassword } from "./components/ResetPassword";
import { logout } from "@/utils";
import { DageRouteItem } from "@/router";
import { useLocation } from "react-router-dom";
import { findRouteByPath } from "../../utils";
import { UserOutlined } from "@ant-design/icons";

export interface LayoutHeaderProps {
  /** 菜单内容 */
  menuData: DageRouteItem[];
}

const isHashRoute = window.location.href.includes("#");
const generateBreadcrumb = (
  pathname: string,
  child: DageRouteItem[]
): {
  title: string;
  href?: string;
}[] => {
  if (!pathname || !child.length) return [];

  const breadcrumb = [];
  const paths = pathname.split("/").filter((path) => path !== "");
  let currentPath = "";

  for (let i = 0; i < paths.length; i++) {
    currentPath += `/${paths[i]}`;
    const item = findRouteByPath(child, currentPath);

    if (item) {
      breadcrumb.push({
        title: item.title,
        href:
          i < paths.length - 1 && item.children
            ? `${isHashRoute ? "#" : ""}${item.redirect || item.path}`
            : undefined,
      });

      if (!item.children) break;
    }
  }

  return breadcrumb;
};

export const LayoutHeader: FC<LayoutHeaderProps> = ({ menuData }) => {
  const { modal } = App.useApp();
  const location = useLocation();
  const breadcrumbItems = useMemo(
    () => generateBreadcrumb(location.pathname, menuData),
    [location, menuData]
  );
  const [resetPwdModalVisible, setResetPwdModalVisible] = useState(false);
  const { userInfo } = useSelector<RootState, RootState["base"]>(
    (state) => state.base
  );

  const handleLogout = useCallback(() => {
    modal.confirm({
      title: "提示",
      content: "确定退出吗?",
      async onOk() {
        await logout();
      },
    });
  }, [modal]);

  return (
    <Header className={style.header}>
      <Breadcrumb items={breadcrumbItems} />

      <Popover
        placement="bottom"
        content={
          <ul className={style.userPopover}>
            <li>
              <Button type="text" onClick={() => setResetPwdModalVisible(true)}>
                修改密码
              </Button>
            </li>
            <li>
              <Button type="text" onClick={handleLogout}>
                退出登录
              </Button>
            </li>
          </ul>
        }
      >
        <div className={style.user}>
          <Avatar
            size={40}
            shape="square"
            icon={<UserOutlined />}
            alt={userInfo?.user.nickName}
          />
          <span>{userInfo?.user.nickName}</span>
        </div>
      </Popover>

      <ResetPassword
        visible={resetPwdModalVisible}
        onCancel={() => setResetPwdModalVisible(false)}
      />
    </Header>
  );
};
