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

import { Lang, 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={styles.container} ref={divRef}>
      <button
        aria-pressed="false"
        className={styles.toggle}
        onClick={toggleOpen}
      >
        <svg focusable="false" className={styles.icon} viewBox="0 0 32 32">
          <use xlinkHref="/_static/img/icons/sprites.svg#icon-globe"></use>
        </svg>
        {languages[currentLanguage]}
        <span className={styles.hiddenAccessible}>Choose language</span>
        <span className={styles.caret}></span>
      </button>
      <ul className={`${styles.dropdown} ${isOpen ? styles.isOpen : ""}`}>
        {Object.keys(urls).map((key) => {
          const url = urls[key as Lang]?.url
          if (url) {
            return (
              <li
                key={key}
                className={`${styles.li} ${currentLanguage === key ? styles.active : ""}`}
              >
                <a className={styles.link} href={url}>
                  {languages[key as Lang]}
                </a>
              </li>
            )
          }
        })}
      </ul>
    </div>
  )
}
