"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useConfirm } from "@/components/shared/use-confirm";

export function PayoutActions({
  payoutId,
  currentStatus,
}: {
  payoutId: number;
  currentStatus: string;
}) {
  const router = useRouter();
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();
  const [loading, setLoading] = useState(false);
  const [showRejectModal, setShowRejectModal] = useState(false);
  const [adminNotes, setAdminNotes] = useState("");

  async function updateStatus(status: string, notes?: string) {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/payouts/${payoutId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status, admin_notes: notes || null }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to update payout");
      } else {
        router.refresh();
      }
    } catch {
      alert("Failed to update payout");
    } finally {
      setLoading(false);
    }
  }

  if (currentStatus === "completed" || currentStatus === "rejected") {
    return (
      <span className="text-text-muted text-sm italic">
        {currentStatus === "completed" ? "Done" : "Rejected"}
      </span>
    );
  }

  return (
    <>
      {confirmDialog}
      <div className="flex items-center gap-2">
        {currentStatus === "pending" && (
          <button
            disabled={loading}
            onClick={async () => {
              const ok = await askConfirm({
                title: "Approve payout?",
                message: "Marking this payout 'processing' is the cue for finance to disburse funds. Are you sure?",
                confirmLabel: "Approve",
              });
              if (!ok) return;
              updateStatus("processing");
            }}
            className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-xs disabled:opacity-50"
          >
            {loading ? "..." : "Approve"}
          </button>
        )}
        {currentStatus === "processing" && (
          <button
            disabled={loading}
            onClick={async () => {
              const ok = await askConfirm({
                title: "Mark complete?",
                message: "This means funds have been disbursed. This action can't be undone.",
                confirmLabel: "Mark complete",
              });
              if (!ok) return;
              updateStatus("completed");
            }}
            className="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-xs disabled:opacity-50"
          >
            {loading ? "..." : "Complete"}
          </button>
        )}
        {(currentStatus === "pending" || currentStatus === "processing") && (
          <button
            disabled={loading}
            onClick={() => setShowRejectModal(true)}
            className="bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-xs disabled:opacity-50"
          >
            Reject
          </button>
        )}
      </div>

      {showRejectModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-surface rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold mb-4">Reject Payout</h3>
            <label className="block text-text-muted text-sm mb-1">
              Admin Notes
            </label>
            <textarea
              value={adminNotes}
              onChange={(e) => setAdminNotes(e.target.value)}
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary mb-4"
              rows={3}
              placeholder="Reason for rejection..."
            />
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowRejectModal(false)}
                className="bg-surface-light hover:bg-surface text-text-muted px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Cancel
              </button>
              <button
                disabled={loading}
                onClick={async () => {
                  setShowRejectModal(false);
                  await updateStatus("rejected", adminNotes);
                  setAdminNotes("");
                }}
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Confirm Reject
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
