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 { RouteType } from "../../types";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { ResetPassword } from "./components/ResetPassword";
import { logout } from "@/utils";

export interface LayoutHeaderProps {
  menu: RouteType | null;
}

export const LayoutHeader: FC<LayoutHeaderProps> = ({ menu }) => {
  const { modal } = App.useApp();
  const [resetPwdModalVisible, setResetPwdModalVisible] = useState(false);
  const { userInfo } = useSelector<RootState, RootState["base"]>(
    (state) => state.base
  );

  const breadcrumb = useMemo(() => {
    const stack: {
      title: string;
      href?: string;
    }[] = [];

    if (!!menu) {
      if (!!menu.parent) {
        stack.push({
          title: menu.parent.label,
          href: menu.parent.key,
        });
      }
      stack.push({
        title: menu.label,
      });
    }

    return stack;
  }, [menu]);

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

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

      <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}
            src={userInfo?.user.thumb}
            alt={userInfo?.user.nickName}
          />
          <span>{userInfo?.user.nickName}</span>
        </div>
      </Popover>

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