"use client"

import { useIntl } from "react-intl"

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

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

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

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

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

export default function MyPagesMenu({
  membership,
  navigation,
  user,
}: MyPagesMenuProps) {
  const intl = useIntl()
  const lang = useLang()
  const { toggleMyPagesMenu, isMyPagesMenuOpen } = useDropdownStore()

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

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