"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function WithdrawButton({
  canWithdraw,
  alreadyRequested,
}: {
  canWithdraw: boolean;
  alreadyRequested: boolean;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function requestWithdrawal() {
    setLoading(true);
    setError(null);
    const res = await fetch("/api/dashboard/payouts/request", { method: "POST" });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error ?? "Could not request a withdrawal");
      return;
    }
    router.refresh();
  }

  if (alreadyRequested) {
    return (
      <div className="text-sm">
        <span className="pill pill-warn">Withdrawal requested</span>
        <p className="text-xs text-be-muted mt-1">
          We&apos;ve been notified and will send your payout shortly.
        </p>
      </div>
    );
  }

  return (
    <div>
      <button
        type="button"
        onClick={requestWithdrawal}
        disabled={!canWithdraw || loading}
        className="rounded-md bg-brand-green px-4 py-2 text-sm font-medium text-white hover:bg-brand-green-deep disabled:opacity-50"
      >
        {loading ? "Requesting…" : "Withdraw available balance"}
      </button>
      {error && <p className="text-xs text-red-500 mt-1">{error}</p>}
    </div>
  );
}
