"use client"
import { useCallback, useEffect, useRef, useState } from "react"

import { languages } from "@/constants/languages"

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

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

export default function Desktop({
  currentLanguage,
  urls,
}: LanguageSwitcherProps) {
  const [isOpen, setIsOpen] = useState(false)
  const divRef = useRef<HTMLDivElement>(null)

  function toggleOpen() {
    setIsOpen(prevIsOpen => !prevIsOpen)
  }

  const close = useCallback(() => {
    setIsOpen(false)
  }, [setIsOpen])

  useEffect(() => {
    function handleClickOutside(evt: Event) {
      const target = evt.target as HTMLElement
      if (divRef.current && target && !divRef.current.contains(target)) {
        close()
      }
    }

    if (divRef.current) {
      document.addEventListener('click', handleClickOutside, false)
    }
    return () => {
      document.removeEventListener('click', handleClickOutside, false)
    }
  }, [close])

  return (
    <div className="dropdown-container navbar-language-selector " ref={divRef}>
      <button
        aria-pressed="false"
        className="navbar-language-selector__toggler"
        data-js="dropdown-toggler"
        onClick={toggleOpen}
      >
        <svg
          focusable="false"
          className="icon icon--xs icon--white"
          viewBox="0 0 32 32"
        >
          <use xlinkHref="/Static/img/icons/sprites.svg#icon-globe"></use>
        </svg>
        {currentLanguage}
        <span className="hidden--accessible">Choose language</span>
        <span className="caret"></span>
      </button>
      <ul className={`${styles.dropdown} ${isOpen ? styles.isOpen : ""}`}>
        <li className={currentLanguage === languages.en ? styles.active : undefined}>
          <a className={styles.link} href={urls.en?.url}>{languages.en}</a>
        </li>
        <li className={currentLanguage === languages.sv ? styles.active : undefined}>
          <a className={styles.link} href={urls.sv?.url}>{languages.sv}</a>
        </li>
        <li className={currentLanguage === languages.no ? styles.active : undefined}>
          <a className={styles.link} href={urls.no?.url}>{languages.no}</a>
        </li>
        {/* When we have 6 languages in Contenstack, danish url should come from urls.da?.url */}
        <li className={currentLanguage === languages.da ? styles.active : undefined}>
          <a className={styles.link} href="https://www.scandichotels.dk/">{languages.da}</a>
        </li>
        <li className={currentLanguage === languages.fi ? styles.active : undefined}>
          <a className={styles.link} href={urls.fi?.url}>{languages.fi}</a>
        </li>
        <li className={currentLanguage === languages.de ? styles.active : undefined}>
          <a className={styles.link} href={urls.de?.url}>{languages.de}</a>
        </li>
      </ul>
    </div>
  )
}
