"use client"

import { useRef } from "react"
import { useIntl } from "react-intl"

import useDropdownStore from "@/stores/main-menu"

import { ChevronDownIcon } from "@/components/Icons"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import useClickOutside from "@/hooks/useClickOutside"
import { useHandleKeyUp } from "@/hooks/useHandleKeyUp"
import { getInitials } from "@/utils/user"

import Avatar from "../Avatar"
import MainMenuButton from "../MainMenuButton"
import MyPagesMenuContent from "../MyPagesMenuContent"

import styles from "./myPagesMenu.module.css"

import { DropdownTypeEnum } from "@/types/components/dropdown/dropdown"
import type { MyPagesMenuProps } from "@/types/components/header/myPagesMenu"

export default function MyPagesMenu({
  membership,
  navigation,
  user,
  membershipLevel,
}: MyPagesMenuProps) {
  const intl = useIntl()
  const myPagesMenuRef = useRef<HTMLDivElement>(null)

  const { toggleDropdown, isMyPagesMenuOpen } = useDropdownStore()

  useHandleKeyUp((event: KeyboardEvent) => {
    if (event.key === "Escape" && isMyPagesMenuOpen) {
      toggleDropdown(DropdownTypeEnum.MyPagesMenu)
    }
  })

  useClickOutside(myPagesMenuRef, isMyPagesMenuOpen, () => {
    toggleDropdown(DropdownTypeEnum.MyPagesMenu)
  })

  return (
    <div className={styles.myPagesMenu} ref={myPagesMenuRef}>
      <MainMenuButton
        onClick={() => toggleDropdown(DropdownTypeEnum.MyPagesMenu)}
      >
        <Avatar initials={getInitials(user.firstName, user.lastName)} />
        <Subtitle type="two" asChild>
          <span>
            {intl.formatMessage({ id: "Hi" })} {user.firstName}!
          </span>
        </Subtitle>
        <ChevronDownIcon
          className={`${styles.chevron} ${isMyPagesMenuOpen ? styles.isExpanded : ""}`}
          color="red"
        />
      </MainMenuButton>
      {isMyPagesMenuOpen ? (
        <div className={styles.dropdown}>
          <MyPagesMenuContent
            membershipLevel={membershipLevel}
            navigation={navigation}
            user={user}
            membership={membership}
            toggleOpenStateFn={() =>
              toggleDropdown(DropdownTypeEnum.MyPagesMenu)
            }
          />
        </div>
      ) : null}
    </div>
  )
}
