"use client"

import { useIntl } from "react-intl"

import { languages } from "@/constants/languages"
import useDropdownStore from "@/stores/main-menu"

import { ChevronDownIcon, GlobeIcon } from "@/components/Icons"
import { useHandleKeyUp } from "@/hooks/useHandleKeyUp"
import useLang from "@/hooks/useLang"

import LanguageSwitcherContent from "./LanguageSwitcherContent"

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

import type { LanguageSwitcherProps } from "@/types/components/languageSwitcher/languageSwitcher"

export default function LanguageSwitcher({
  urls,
  type,
}: LanguageSwitcherProps) {
  const intl = useIntl()
  const currentLanguage = useLang()
  const { toggleLanguageSwitcher, isLanguageSwitcherOpen } = useDropdownStore()

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

  return (
    <div className={styles.languageSwitcher}>
      <button
        type="button"
        className={styles.button}
        aria-label={intl.formatMessage({
          id: isLanguageSwitcherOpen
            ? "Close language menu"
            : "Open language menu",
        })}
        onClick={toggleLanguageSwitcher}
      >
        <GlobeIcon width={20} height={20} color="burgundy" />
        <span>{languages[currentLanguage]}</span>
        <ChevronDownIcon
          className={`${styles.chevron} ${isLanguageSwitcherOpen ? styles.isExpanded : ""}`}
          width={20}
          height={20}
          color="burgundy"
        />
      </button>

      <div
        className={`${styles.dropdown} ${isLanguageSwitcherOpen ? styles.isExpanded : ""}`}
      >
        {isLanguageSwitcherOpen ? (
          <LanguageSwitcherContent urls={urls} type={type} />
        ) : null}
      </div>
    </div>
  )
}
