import { MoreOutlined } from "@ant-design/icons";
import { SessionType } from "@openim/wasm-client-sdk";
import { Dropdown, Layout } from "antd";
import { t } from "i18next";
import { memo, useEffect, useRef } from "react";

import { OverlayVisibleHandle } from "@/hooks/useOverlayVisible";
import { useConversationStore } from "@/store";
import { emit } from "@/utils/events";

import GroupSetting from "../GroupSetting";
import SingleSetting from "../SingleSetting";

const ChatHeader = () => {
  const singleSettingRef = useRef<OverlayVisibleHandle>(null);
  const groupSettingRef = useRef<OverlayVisibleHandle>(null);

  const currentConversation = useConversationStore(
    (state) => state.currentConversation,
  );

  useEffect(() => {
    if (singleSettingRef.current?.isOverlayOpen) {
      singleSettingRef.current?.closeOverlay();
    }
    if (groupSettingRef.current?.isOverlayOpen) {
      groupSettingRef.current?.closeOverlay();
    }
  }, [currentConversation?.conversationID]);

  const isSingleSession = currentConversation?.conversationType === SessionType.Single;

  const menuItems = isSingleSession
    ? [{ key: "viewProfile", label: t("placeholder.viewProfile") }]
    : [{ key: "groupSetting", label: t("placeholder.groupSetting") }];

  const onMenuClick = ({ key }: { key: string }) => {
    switch (key) {
      case "viewProfile":
        emit("OPEN_USER_CARD", {
          userID: currentConversation?.userID,
          isSelf: false,
        });
        break;
      case "groupSetting":
        groupSettingRef.current?.openOverlay();
        break;
      default:
        break;
    }
  };

  return (
    <Layout.Header
      className="app-drag relative border-b border-b-[var(--gap-text)] bg-white px-4"
      style={{ height: 56, lineHeight: "56px", paddingInline: 16 }}
    >
      <div className="flex h-full items-center leading-none">
        <div className="flex flex-1 items-center overflow-hidden">
          <div className="truncate text-base font-bold">
            {currentConversation?.showName}
          </div>
        </div>
        <Dropdown
          menu={{ items: menuItems, onClick: onMenuClick }}
          trigger={["click"]}
          placement="bottomRight"
        >
          <MoreOutlined
            className="app-no-drag cursor-pointer p-1 text-[20px] text-[var(--sub-text)] hover:text-[var(--primary)]"
            rev={undefined}
          />
        </Dropdown>
        {Boolean(window.electronAPI) && <div className="w-28 shrink-0" />}
      </div>
      <SingleSetting ref={singleSettingRef} />
      <GroupSetting ref={groupSettingRef} />
    </Layout.Header>
  );
};

export default memo(ChatHeader);
