"use client"

import { type AppLocale, localeLabels, locales } from "@cms/i18n"
import { useRouter } from "next/navigation"
import { useTransition } from "react"

import { ADMIN_LOCALE_COOKIE } from "@/i18n/shared"
import { useAdminI18n, useAdminT } from "@/providers/admin-i18n-provider"

export function AdminLocaleSwitcher() {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()
  const { locale } = useAdminI18n()
  const t = useAdminT()

  return (
    <label className="inline-flex items-center gap-2 text-sm text-neutral-700">
      <span>{t("common.language", "Language")}</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
          // biome-ignore lint/suspicious/noDocumentCookie: locale preference is intentionally persisted client-side.
          document.cookie = `${ADMIN_LOCALE_COOKIE}=${nextLocale}; Path=/; Max-Age=31536000; SameSite=Lax`

          startTransition(() => {
            router.refresh()
          })
        }}
      >
        {locales.map((value) => (
          <option key={value} value={value}>
            {t(`common.localeNames.${value}`, localeLabels[value])} ({localeLabels[value]})
          </option>
        ))}
      </select>
    </label>
  )
}
