"use client"

import { useRouter } from "next/navigation"
import { useState } from "react"

import { dashboardCsrfHeader } from "@/lib/csrf.client"
import { cn } from "@/lib/utils"

import {
  formatPibOption,
  type PibClassOption,
} from "../_lib/pib-class-options"
import { LIST_HREF } from "./schema"
import { useChanged } from "@/hooks/use-changed";

type Props = {
  id: string
  value: string
  options: PibClassOption[]
  className?: string
}

export function IsinAssetMasterPibSelect({ id, value, options, className }: Props) {
  const router = useRouter()
  const [current, setCurrent] = useState(value)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Re-sync when the server sends a new value; local selection wins until then.
  if (useChanged(value)) {
    setCurrent(value)
  }

  const optionByCode = new Map(options.map((opt) => [opt.code, opt]))
  if (current && !optionByCode.has(current)) {
    optionByCode.set(current, { code: current, label: current })
  }
  const allOptions = Array.from(optionByCode.values()).sort((a, b) =>
    a.code.localeCompare(b.code)
  )

  async function onChange(next: string) {
    if (next === current || busy) return
    setBusy(true)
    setError(null)
    const previous = current
    setCurrent(next)
    try {
      const res = await fetch(`${LIST_HREF}/${id}/update-pib`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          ...dashboardCsrfHeader(),
        },
        body: JSON.stringify({ id, pib_class: next }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.status === "error") {
        setCurrent(previous)
        throw new Error(json?.message || "Could not update PIB.")
      }
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : "Could not update PIB.")
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className={cn("flex flex-col gap-0.5", className)}>
      <select
        className={cn(
          "h-8 max-w-[15rem] rounded border border-input bg-background px-2 text-xs",
          "disabled:cursor-not-allowed disabled:opacity-50"
        )}
        value={current}
        disabled={busy}
        onChange={(e) => void onChange(e.target.value)}
        aria-label="PIB class"
      >
        <option value="">—</option>
        {allOptions.map((opt) => (
          <option key={opt.code} value={opt.code}>
            {formatPibOption(opt)}
          </option>
        ))}
      </select>
      {error ? <span className="text-[10px] text-destructive">{error}</span> : null}
    </div>
  )
}
