"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/MaterialIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"

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 { trackLanguageSwitchClick } from "@/utils/tracking/navigation"

import SkeletonShimmer from "../SkeletonShimmer"
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({
    defaultMessage: "Close language menu",
  })
  const openMsg = intl.formatMessage({
    defaultMessage: "Open language menu",
  })

  function onLanguageSwitch(toLang: string) {
    trackLanguageSwitchClick(currentLanguage, 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>
  )
}
