"use client"

import { usePathname } from "next/navigation"
import { useRef } from "react"
import FocusLock from "react-focus-lock"
import { useIntl } from "react-intl"

import { MaterialIcon } from "@scandic-hotels/design-system/Icons"

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

import useClickOutside from "@/hooks/useClickOutside"
import { useHandleKeyUp } from "@/hooks/useHandleKeyUp"
import useLang from "@/hooks/useLang"

import SkeletonShimmer from "../SkeletonShimmer"
import Caption from "../TempDesignSystem/Text/Caption"
import LanguageSwitcherContainer from "./LanguageSwitcherContainer"
import LanguageSwitcherContent from "./LanguageSwitcherContent"
import { languageSwitcherVariants } from "./variants"

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

import { DropdownTypeEnum } from "@/types/components/dropdown/dropdown"
import {
  type LanguageSwitcherProps,
  LanguageSwitcherTypesEnum,
} from "@/types/components/languageSwitcher/languageSwitcher"

export default function LanguageSwitcher({ type }: LanguageSwitcherProps) {
  const intl = useIntl()
  const currentLanguage = useLang()
  const {
    toggleDropdown,
    isFooterLanguageSwitcherOpen,
    isHeaderLanguageSwitcherMobileOpen,
    isHeaderLanguageSwitcherOpen,
  } = useDropdownStore()

  const pathName = usePathname()

  const { data: languagesResponse, isLoading } =
    trpc.contentstack.languageSwitcher.get.useQuery({
      pathName,
      lang: currentLanguage,
    })

  const languageSwitcherRef = useRef<HTMLDivElement>(null)
  const isFooter = type === LanguageSwitcherTypesEnum.Footer
  const isHeader = !isFooter
  const globeIconSize = type === "desktopHeader" ? 16 : 20

  const position = isFooter ? "footer" : "header"

  const dropdownType = {
    footer: DropdownTypeEnum.FooterLanguageSwitcher,
    desktopHeader: DropdownTypeEnum.HeaderLanguageSwitcher,
    mobileHeader: DropdownTypeEnum.HeaderLanguageSwitcherMobile,
  }[type]

  const isLanguageSwitcherOpen =
    (isFooter && isFooterLanguageSwitcherOpen) ||
    (isHeader &&
      (isHeaderLanguageSwitcherOpen || isHeaderLanguageSwitcherMobileOpen))

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

  function handleClick() {
    const scrollPosition = window.scrollY
    toggleDropdown(dropdownType)

    requestAnimationFrame(() => {
      window.scrollTo(0, scrollPosition)
    })
  }
  useClickOutside(
    languageSwitcherRef,
    isLanguageSwitcherOpen && !isHeaderLanguageSwitcherMobileOpen,
    () => toggleDropdown(dropdownType)
  )

  const classNames = languageSwitcherVariants({ position })

  const closeMsg = intl.formatMessage({ id: "Close language menu" })
  const openMsg = intl.formatMessage({ id: "Open language menu" })

  if (isLoading) {
    return <SkeletonShimmer width="12ch" />
  }

  if (!languagesResponse?.urls) {
    return null
  }

  return (
    <div className={classNames} ref={languageSwitcherRef}>
      <button
        type="button"
        className={styles.button}
        aria-label={isLanguageSwitcherOpen ? closeMsg : openMsg}
        onClick={handleClick}
      >
        <MaterialIcon icon="globe" size={globeIconSize} />
        <Caption className={styles.buttonText} type="regular" asChild>
          <span>{languages[currentLanguage]}</span>
        </Caption>
        <MaterialIcon
          icon="keyboard_arrow_down"
          className={`${styles.chevron} ${isLanguageSwitcherOpen ? styles.isExpanded : ""}`}
          size={20}
        />
      </button>

      <div
        className={`${styles.dropdown} ${isLanguageSwitcherOpen ? styles.isExpanded : ""}`}
      >
        <FocusLock returnFocus={true} disabled={!isLanguageSwitcherOpen}>
          <LanguageSwitcherContainer type={type}>
            <LanguageSwitcherContent
              urls={languagesResponse.urls}
              onLanguageSwitch={() => toggleDropdown(dropdownType)}
            />
          </LanguageSwitcherContainer>
        </FocusLock>
      </div>
    </div>
  )
}
