"use client"

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

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

import { ChevronDownSmallIcon } from "@/components/Icons"
import SkeletonShimmer from "@/components/SkeletonShimmer"
import Body from "@/components/TempDesignSystem/Text/Body"
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)} />
        <Body textTransform="bold" color="baseTextHighContrast" asChild>
          <span>
            {intl.formatMessage({ id: "Hi" })} {user.firstName}!
          </span>
        </Body>
        <ChevronDownSmallIcon
          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>
  )
}

export function MyPagesMenuSkeleton() {
  return (
    <div className={styles.myPagesMenu}>
      <MainMenuButton>
        <Avatar />
        <SkeletonShimmer width="10ch" />
        <ChevronDownSmallIcon className={`${styles.chevron}`} color="red" />
      </MainMenuButton>
    </div>
  )
}
