"use client"

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

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

type Props = {
  id: string
  status: string
}

export function IsinAssetMasterDetailActions({ id, status }: Props) {
  const router = useRouter()
  const [busy, setBusy] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  async function post(action: "lock" | "unlock" | "recompute") {
    setBusy(action)
    setError(null)
    try {
      const res = await fetch(`${LIST_HREF}/${id}/${action}`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          ...dashboardCsrfHeader(),
        },
        body: JSON.stringify({ id }),
      })
      const json = await res.json().catch(() => ({}))
      if (!res.ok || json?.status === "error") {
        throw new Error(json?.message || `Failed to ${action}`)
      }
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : `Failed to ${action}`)
    } finally {
      setBusy(null)
    }
  }

  const btn =
    "rounded border px-2.5 py-1 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-50"

  return (
    <div className="flex flex-col items-end gap-1">
      <div className="flex flex-wrap gap-2">
        {status === "locked" ? (
          <button
            type="button"
            className={cn(btn, "border-border bg-background hover:bg-muted")}
            disabled={busy !== null}
            onClick={() => void post("unlock")}
          >
            {busy === "unlock" ? "Unlocking…" : "Unlock"}
          </button>
        ) : (
          <button
            type="button"
            className={cn(btn, "border-amber-600/50 bg-amber-50 text-amber-950 hover:bg-amber-100")}
            disabled={busy !== null}
            onClick={() => void post("lock")}
          >
            {busy === "lock" ? "Locking…" : "Lock"}
          </button>
        )}
        <button
          type="button"
          className={cn(btn, "border-border bg-background hover:bg-muted")}
          disabled={busy !== null || status === "locked"}
          onClick={() => void post("recompute")}
        >
          {busy === "recompute" ? "Recomputing…" : "Recompute"}
        </button>
      </div>
      {error ? <p className="text-xs text-destructive">{error}</p> : null}
    </div>
  )
}
