'use client'

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

/**
 * Row actions on /admin/purchases. Only the two actions the spec allows
 * (task §24): re-run reconciliation and flag / clear the reconciliation flag.
 * No "mark as paid" — payment status is set only by a verified confirmation.
 */
export function PurchaseActions({ purchaseId, flagged }: { purchaseId: string; flagged: boolean }) {
  const router = useRouter()
  const [busy, setBusy] = useState<'reconcile' | 'flag' | 'unflag' | null>(null)
  const [message, setMessage] = useState<string | null>(null)

  async function run(op: 'reconcile' | 'flag' | 'unflag') {
    setBusy(op)
    setMessage(null)
    try {
      const res = await fetch('/api/admin/purchases', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ op, purchase_id: purchaseId }),
      })
      const body = (await res.json().catch(() => ({}))) as { error?: string; result?: { ok: boolean; reason?: string; status?: string; changed?: boolean } }
      if (!res.ok) {
        setMessage(body.error ?? `Request failed (${res.status}).`)
      } else if (op === 'reconcile') {
        const r = body.result
        setMessage(r?.ok ? `Reconciled: ${r.status}${r.changed ? ' (changed)' : ' (no change)'}` : `Reconciliation did not apply: ${r?.reason ?? 'unknown'}`)
      } else {
        setMessage(op === 'flag' ? 'Flagged for reconciliation.' : 'Flag cleared.')
      }
      router.refresh()
    } catch {
      setMessage('Network error.')
    } finally {
      setBusy(null)
    }
  }

  const btn = 'rounded-md border px-2 py-1 text-xs font-semibold text-neutral-800 hover:bg-neutral-50 disabled:opacity-50'
  return (
    <div className="flex flex-col gap-1">
      <div className="flex flex-wrap gap-1">
        <button type="button" className={btn} disabled={busy !== null} onClick={() => run('reconcile')}>
          {busy === 'reconcile' ? 'Reconciling…' : 'Re-run reconciliation'}
        </button>
        {flagged ? (
          <button type="button" className={btn} disabled={busy !== null} onClick={() => run('unflag')}>
            {busy === 'unflag' ? 'Clearing…' : 'Clear flag'}
          </button>
        ) : (
          <button type="button" className={btn} disabled={busy !== null} onClick={() => run('flag')}>
            {busy === 'flag' ? 'Flagging…' : 'Flag for reconciliation'}
          </button>
        )}
      </div>
      {message && <p className="text-[11px] text-neutral-600">{message}</p>}
    </div>
  )
}
