"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { buttonClass } from "@/components/ui";

export default function FinancingRequestForm() {
  const router = useRouter();
  const [amount, setAmount] = useState("");
  const [note, setNote] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const amountCents = Math.round(Number(amount) * 100);
    if (!Number.isFinite(amountCents) || amountCents <= 0) {
      setError("Enter a valid amount");
      return;
    }
    setError(null);
    setLoading(true);
    const res = await fetch("/api/financing/request", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ amountCents, note: note.trim() || undefined }),
    });
    const data = await res.json().catch(() => ({}));
    setLoading(false);
    if (!res.ok) {
      setError(data.error || "Request failed");
      return;
    }
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label className="block text-sm font-medium mb-1 text-be-text">Amount (KES)</label>
        <input
          required
          type="number"
          min="1"
          step="1"
          placeholder="500000"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          className="input"
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1 text-be-text">
          What&apos;s it for? (optional)
        </label>
        <textarea
          rows={3}
          placeholder="Working capital for next event's venue deposit"
          value={note}
          onChange={(e) => setNote(e.target.value)}
          className="input"
        />
      </div>
      {error && <p className="text-sm text-[color:var(--pill-danger-fg)]">{error}</p>}
      <button type="submit" disabled={loading} className={buttonClass("primary")}>
        {loading ? "Requesting…" : "Request funds"}
      </button>
      <p className="text-xs text-be-muted">
        Repayment is a flat 12% of each future payout until the advance is repaid. Approval typically
        takes under 48h.
      </p>
    </form>
  );
}
