"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 { type FriendsMembership, 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 { User } from "@/types/user"
import type { LoyaltyLevel } from "@/server/routers/contentstack/loyaltyLevel/output"

export type MyPagesMenuProps = {
  user: Pick<User, "firstName" | "lastName">
  membership?: FriendsMembership | null
  membershipLevel: LoyaltyLevel | null
}

export default function MyPagesMenu({
  user,
  membership,
  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 data-hj-suppress>
            {intl.formatMessage(
              { id: "Hi {firstName}!" },
              { firstName: user.firstName }
            )}
          </span>
        </Body>
        <ChevronDownSmallIcon
          className={`${styles.chevron} ${isMyPagesMenuOpen ? styles.isExpanded : ""}`}
          color="red"
        />
      </MainMenuButton>
      {isMyPagesMenuOpen ? (
        <div className={styles.dropdown}>
          <MyPagesMenuContent
            membershipLevel={membershipLevel}
            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>
  )
}
