"use client"

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

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { type Lang, languages } from "@/constants/languages"
import { env } from "@/env/client"

import Link from "@/components/TempDesignSystem/Link"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import useLang from "@/hooks/useLang"

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) {
  const intl = useIntl()
  const currentLanguage = useLang()

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

  const pathname = usePathname()
  const relValue = env.NEXT_PUBLIC_HIDE_FOR_NEXT_RELEASE
    ? "nofollow"
    : undefined

  return (
    <div className={styles.languageWrapper}>
      <Subtitle className={styles.subtitle} type="two">
        {intl.formatMessage({
          defaultMessage: "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)}
                  rel={relValue}
                  onClick={onLanguageSwitch}
                  keepSearchParams
                >
                  {languages[key]}
                  {isActive ? (
                    <MaterialIcon
                      icon="check"
                      color="Icon/Interactive/Default"
                    />
                  ) : null}
                </Link>
              </li>
            )
          }
        })}
      </ul>
    </div>
  )
}
