"use client"

import Link from "next/link"
import { useState } from "react"

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

import { CheckIcon, ChevronDownIcon, GlobeIcon } from "@/components/Icons"
import useLang from "@/hooks/useLang"

import Button from "../Button"

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

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

export default function LanguageSwitcher({ urls }: LanguageSwitcherProps) {
  const currentLanguage = useLang()
  const [isExpanded, setIsExpanded] = useState(false)

  function toggleExpand() {
    setIsExpanded((prev) => !prev)
  }

  const urlKeys = Object.keys(urls) as Lang[]

  return (
    <div className={styles.languageSwitcher}>
      <Button onClick={toggleExpand}>
        <GlobeIcon width={20} height={20} color="burgundy" />
        <span>{languages[currentLanguage]}</span>
        <ChevronDownIcon
          className={`${styles.chevron} ${isExpanded ? styles.isExpanded : ""}`}
          width={20}
          height={20}
          color="burgundy"
        />
      </Button>
      <div
        className={`${styles.dropdown} ${isExpanded ? styles.isExpanded : ""}`}
      >
        <ul className={styles.list}>
          {urlKeys.map((key) => {
            const url = urls[key]?.url
            const isActive = currentLanguage === key
            if (url) {
              return (
                <li key={key}>
                  <Link
                    className={`${styles.link} ${isActive ? styles.active : ""}`}
                    color="burgundy"
                    href={url}
                  >
                    {languages[key]}
                    {isActive ? <CheckIcon color="burgundy" /> : null}
                  </Link>
                </li>
              )
            }
          })}
        </ul>
      </div>
    </div>
  )
}
