import { useState } from "react"

import { useArcadiaClient } from "@crema/arcadia-core-client"
import { useToast } from "@crema/notification-ui"

import { TenantSection, Field } from "~/components/tenant-detail/section"
import { NativeSelect, NativeSelectOption } from "~/components/ui/native-select"
import {
  updateLocalization,
  TENANT_LOCALES,
  TENANT_CURRENCIES,
  COMMON_TIMEZONES,
} from "~/lib/arcadia/tenants"
import type { TenantTabProps } from "~/routes/tenants.$id"

export function LocalizationTab({ tenant, reload }: TenantTabProps) {
  const arcadia = useArcadiaClient()
  const toast = useToast()

  const current = tenant.localization
  const [locale, setLocale] = useState(current?.locale ?? "")
  const [timezone, setTimezone] = useState(current?.timezone ?? "")
  const [currency, setCurrency] = useState(current?.currency ?? "")
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<unknown>(null)

  // The tenant's real timezone might be an IANA name outside our curated list —
  // prepend it so the select shows the current value instead of silently
  // snapping to the first option.
  const timezoneOptions =
    current?.timezone && !COMMON_TIMEZONES.includes(current.timezone)
      ? [current.timezone, ...COMMON_TIMEZONES]
      : COMMON_TIMEZONES

  const dirty =
    locale !== (current?.locale ?? "") ||
    timezone !== (current?.timezone ?? "") ||
    currency !== (current?.currency ?? "")

  const save = async () => {
    setSaving(true)
    setError(null)
    try {
      await updateLocalization(arcadia, tenant.id, { locale, timezone, currency })
      await reload()
      toast.success("Localization updated")
    } catch (err) {
      setError(err)
    } finally {
      setSaving(false)
    }
  }

  return (
    <TenantSection
      title="Localization"
      description="Default locale, timezone, and currency for this tenant."
      onSubmit={save}
      saving={saving}
      error={error}
      errorContext="update localization"
      dirty={dirty}
      dataAction="tenant-detail-localization-save"
    >
      <Field label="Locale" htmlFor="tenant-detail-localization-locale">
        <NativeSelect
          id="tenant-detail-localization-locale"
          className="w-full"
          value={locale}
          onChange={(e) => setLocale(e.target.value)}
          data-action="tenant-detail-localization-locale"
        >
          {TENANT_LOCALES.map((l) => (
            <NativeSelectOption key={l} value={l}>
              {l}
            </NativeSelectOption>
          ))}
        </NativeSelect>
      </Field>

      <Field label="Currency" htmlFor="tenant-detail-localization-currency">
        <NativeSelect
          id="tenant-detail-localization-currency"
          className="w-full"
          value={currency}
          onChange={(e) => setCurrency(e.target.value)}
          data-action="tenant-detail-localization-currency"
        >
          {TENANT_CURRENCIES.map((c) => (
            <NativeSelectOption key={c} value={c}>
              {c}
            </NativeSelectOption>
          ))}
        </NativeSelect>
      </Field>

      <Field label="Timezone" htmlFor="tenant-detail-localization-timezone">
        <NativeSelect
          id="tenant-detail-localization-timezone"
          className="w-full"
          value={timezone}
          onChange={(e) => setTimezone(e.target.value)}
          data-action="tenant-detail-localization-timezone"
        >
          {timezoneOptions.map((tz) => (
            <NativeSelectOption key={tz} value={tz}>
              {tz}
            </NativeSelectOption>
          ))}
        </NativeSelect>
      </Field>
    </TenantSection>
  )
}
