"use client"

import { usePathname, useSearchParams } from "next/navigation"
import { useIntl } from "react-intl"

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

import { CheckIcon } from "@/components/Icons"
import Link from "@/components/TempDesignSystem/Link"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import useLang from "@/hooks/useLang"
import { useTrapFocus } from "@/hooks/useTrapFocus"

import { replaceUrlPart } from "./utils"

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

import type { LanguageSwitcherContentProps } from "@/types/components/languageSwitcher/languageSwitcher"

export default function LanguageSwitcherContent({
  urls,
  onLanguageSwitch,
}: LanguageSwitcherContentProps) {
  console.log(urls)
  const intl = useIntl()
  const currentLanguage = useLang()

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

  const pathname = usePathname()

  return (
    <div className={styles.languageSwitcherContent} ref={languageSwitcherRef}>
      <div className={styles.languageWrapper}>
        <Subtitle className={styles.subtitle} type="two">
          {intl.formatMessage({ id: "Select your language" })}
        </Subtitle>
        <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 : ""}`}
                    href={replaceUrlPart(pathname, url)}
                    onClick={onLanguageSwitch}
                    keepSearchParams
                  >
                    {languages[key]}
                    {isActive ? <CheckIcon color="burgundy" /> : null}
                  </Link>
                </li>
              )
            }
          })}
        </ul>
      </div>
    </div>
  )
}
