"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { formatPrice } from "@/lib/format";
import type { FinancingStatus } from "@/lib/types";

export default function FinancingActions({
  requestId,
  status,
  amountCents,
  currency,
}: {
  requestId: string;
  status: FinancingStatus;
  amountCents: number;
  currency: string;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function post(url: string, body: Record<string, unknown>) {
    setError(null);
    setLoading(true);
    const res = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error || "Action failed");
      return;
    }
    router.refresh();
  }

  async function approve() {
    if (!confirm(`Approve this ${formatPrice(amountCents, currency)} advance request?`)) return;
    await post("/api/financing/resolve", { requestId, action: "approve" });
  }

  async function reject() {
    const note = prompt("Reason for rejecting (optional):") ?? undefined;
    await post("/api/financing/resolve", { requestId, action: "reject", note });
  }

  async function disburse() {
    const reference = prompt(
      `Record disbursement of ${formatPrice(amountCents, currency)}. Enter a reference (M-Pesa code, bank ref, etc.):`
    );
    if (!reference) return;
    await post("/api/financing/disburse", { requestId, reference });
  }

  if (status === "pending") {
    return (
      <div className="flex flex-col items-end gap-1">
        <div className="flex gap-1.5">
          <button type="button" onClick={approve} disabled={loading} className="be-act be-act-primary">
            Approve
          </button>
          <button type="button" onClick={reject} disabled={loading} className="be-act be-act-ghost">
            Reject
          </button>
        </div>
        {error && <span className="text-xs text-[color:var(--pill-danger-fg)]">{error}</span>}
      </div>
    );
  }

  if (status === "approved") {
    return (
      <div className="flex flex-col items-end gap-1">
        <button type="button" onClick={disburse} disabled={loading} className="be-act be-act-primary">
          {loading ? "Working…" : "Disburse"}
        </button>
        {error && <span className="text-xs text-[color:var(--pill-danger-fg)]">{error}</span>}
      </div>
    );
  }

  return null;
}
