"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function RefundResolveActions({ requestId }: { requestId: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  // Set when an auto gateway refund fails, so we can offer the manual fallback.
  const [gatewayFailed, setGatewayFailed] = useState(false);

  async function resolve(action: "approve" | "reject", manual = false) {
    if (action === "approve" && !manual) {
      if (
        !confirm(
          "Issue this refund? The buyer will be refunded via their original payment method, the order marked refunded, and its tickets voided."
        )
      ) {
        return;
      }
    }
    if (action === "approve" && manual) {
      if (
        !confirm(
          "Record this as a manually-handled refund? No gateway refund will be sent — the order is marked refunded and its tickets voided. Move the money back to the buyer yourself."
        )
      ) {
        return;
      }
    }
    const note =
      action === "reject" ? prompt("Reason for rejecting (optional):") ?? undefined : undefined;
    setError(null);
    setLoading(true);
    const res = await fetch("/api/refunds/resolve", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ requestId, action, note, manual }),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error || "Action failed");
      // The gateway rejected the refund — offer to record it manually instead.
      if (data.gatewayFailed) setGatewayFailed(true);
      return;
    }
    router.refresh();
  }

  return (
    <div className="flex flex-col items-end gap-1">
      <div className="flex gap-1.5">
        <button
          type="button"
          onClick={() => resolve("approve")}
          disabled={loading}
          className="be-act be-act-primary"
        >
          Issue refund
        </button>
        <button
          type="button"
          onClick={() => resolve("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>}
      {gatewayFailed && (
        <button
          type="button"
          onClick={() => resolve("approve", true)}
          disabled={loading}
          className="be-act be-act-warn"
        >
          Record manual refund instead
        </button>
      )}
    </div>
  );
}
