"use client"

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

import { languages } from "@scandic-hotels/common/constants/language"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import SkeletonShimmer from "@scandic-hotels/design-system/SkeletonShimmer"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { trackLanguageSwitchClick } from "@scandic-hotels/tracking/navigation"
import { trpc } from "@scandic-hotels/trpc/client"

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

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

import LanguageSwitcherContainer from "./LanguageSwitcherContainer"
import LanguageSwitcherContent from "./LanguageSwitcherContent"
import { setLanguageCookie } from "./setLanguageCookie"
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: "common.closeLanguageMenu",
    defaultMessage: "Close language menu",
  })
  const openMsg = intl.formatMessage({
    id: "common.openLanguageMenu",
    defaultMessage: "Open language menu",
  })

  function onLanguageSwitch(toLang: string) {
    trackLanguageSwitchClick(currentLanguage, toLang)
    setLanguageCookie(toLang)
    toggleDropdown(dropdownType)
  }

  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} color="CurrentColor" />
        <Typography
          variant="Body/Supporting text (caption)/smRegular"
          className={styles.buttonText}
        >
          <span>{languages[currentLanguage]}</span>
        </Typography>
        <MaterialIcon
          icon="keyboard_arrow_down"
          className={`${styles.chevron} ${isLanguageSwitcherOpen ? styles.isExpanded : ""}`}
          size={20}
          color="CurrentColor"
        />
      </button>

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