"use client"

import { type AppLocale, localeLabels, locales } from "@cms/i18n"
import { useLocale, useTranslations } from "next-intl"
import { useEffect, useTransition } from "react"

import { usePathname, useRouter } from "@/i18n/navigation"
import { useLocaleStore } from "@/store/locale"

export function LanguageSwitcher() {
  const t = useTranslations("LanguageSwitcher")
  const currentLocale = useLocale() as AppLocale
  const pathname = usePathname()
  const router = useRouter()
  const [isPending, startTransition] = useTransition()

  const locale = useLocaleStore((state) => state.locale)
  const setLocale = useLocaleStore((state) => state.setLocale)

  useEffect(() => {
    if (locale !== currentLocale) {
      setLocale(currentLocale)
    }
  }, [currentLocale, locale, setLocale])

  return (
    <label className="inline-flex items-center gap-2 text-sm text-neutral-700">
      <span>{t("label")}</span>
      <select
        className="rounded-md border border-neutral-300 bg-white px-2 py-1 text-sm"
        value={locale}
        disabled={isPending}
        onChange={(event) => {
          const nextLocale = event.target.value as AppLocale
          setLocale(nextLocale)

          startTransition(() => {
            router.replace(pathname, { locale: nextLocale })
          })
        }}
      >
        {locales.map((value) => (
          <option key={value} value={value}>
            {t(`localeNames.${value}`)} ({localeLabels[value]})
          </option>
        ))}
      </select>
    </label>
  )
}
