"use client"

import { errorMessageOr } from "@/lib/toast-api-error";

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

import { DeleteConfirmDialog } from "@/components/shared/delete-confirm-dialog"
import { LIST_HREF } from "./schema"
import { dashboardCsrfHeader } from "@/lib/csrf.client"
import { cn } from "@/lib/utils"

type Props = {
  id: string
  status: string
  acAtEditAllowed: boolean
  aClass: string
  aType: string
  pibClass: string
  isin: string
}

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

  const [confirmOpen, setConfirmOpen] = useState(false)

  async function post(action: "lock" | "unlock" | "recompute" | "propagateTransactions") {
    setBusy(action)
    setError(null)
    setSuccess(null)
    const actionPath =
      action === "propagateTransactions" ? "propagate-transactions" : action
    try {
      const res = await fetch(`${LIST_HREF}/${id}/${actionPath}`, {
        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
            || (action === "propagateTransactions"
              ? "Failed to update transactions."
              : `Failed to ${action}`),
        )
      }
      if (action === "propagateTransactions" && typeof json?.message === "string") {
        setSuccess(json.message)
      }
      router.refresh()
    } catch (e) {
      setError(errorMessageOr(e, `Failed to ${action}`))
      if (action === "propagateTransactions") {
        throw e
      }
    } finally {
      setBusy(null)
    }
  }

  const canPropagate =
    acAtEditAllowed && status === "locked" && aClass.trim() !== ""

  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>
        <button
          type="button"
          className={cn(btn, "border-sky-600/50 bg-sky-50 text-sky-950 hover:bg-sky-100")}
          disabled={busy !== null || !canPropagate}
          title={
            !canPropagate
              ? "Lock the master with a valid asset class before updating transactions."
              : "Push AC/AT to ledger rows and refresh PIB on overall summary."
          }
          onClick={() => setConfirmOpen(true)}
        >
          {busy === "propagateTransactions" ? "Updating…" : "Update transactions"}
        </button>
      </div>
      {success ? <p className="text-xs text-emerald-700">{success}</p> : null}
      {error ? <p className="text-xs text-destructive">{error}</p> : null}
      <DeleteConfirmDialog
        open={confirmOpen}
        onOpenChange={setConfirmOpen}
        title={`Update transactions for ${isin}?`}
        description={
          <>
            Locked classification is applied to ledger rows across all portfolios.
            Asset class {aClass || "—"}, type {aType || "—"}, PIB {pibClass || "—"}.
          </>
        }
        confirmLabel="Update transactions"
        confirmingLabel="Updating…"
        confirmVariant="default"
        onConfirm={async () => {
          await post("propagateTransactions")
        }}
      />
    </div>
  )
}
