"use client";
import { useEffect, useState } from "react";

type Tip = {
  id: string;
  name: string;
  message: string | null;
  amount: number;
  realAmount: number | null;
  isRecurring: boolean;
  isPublic: boolean;
  status: string;
  createdAt: string;
};

export default function AdminSupportersPage() {
  const [tips, setTips] = useState<Tip[]>([]);
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");
  const [amount, setAmount] = useState("");
  const [isRecurring, setIsRecurring] = useState(false);
  const [isPublic, setIsPublic] = useState(true);
  const [date, setDate] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  async function load() {
    const res = await fetch("/api/admin/supporters");
    setTips(await res.json());
  }
  useEffect(() => { load(); }, []);

  async function submit() {
    setError("");
    setSaving(true);
    const res = await fetch("/api/admin/supporters", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, message, amount, isRecurring, isPublic, date: date || undefined }),
    });
    const data = await res.json();
    setSaving(false);
    if (!res.ok) {
      setError(data.error);
      return;
    }
    setName(""); setMessage(""); setAmount(""); setIsRecurring(false); setIsPublic(true); setDate("");
    load();
  }

  const inputCls = "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  return (
    <div>
      <h2 className="text-lg font-semibold mb-1">Supporters (Tips Table)</h2>
      <p className="text-xs text-neutral-500 mb-4">
        This data lives in the <code>tips</code> database table. Entries created through the checkout flow
        come from Stripe payments; use the form below only to record <b>real support you've actually received</b>{" "}
        through another channel (cash, bank transfer, in person, etc.) so it shows correctly in the public
        "Partners in Mission" list and the Funding Dashboard.
      </p>

      <div className="card p-5 mb-6 space-y-3">
        <h3 className="font-semibold text-sm">Manually Record a Supporter</h3>
        <div className="grid sm:grid-cols-2 gap-3">
          <div>
            <label className="block text-xs text-neutral-500 mb-1">Supporter name *</label>
            <input value={name} onChange={(e) => setName(e.target.value)} className={inputCls} />
          </div>
          <div>
            <label className="block text-xs text-neutral-500 mb-1">Amount ($) *</label>
            <input type="number" step="0.01" value={amount} onChange={(e) => setAmount(e.target.value)} className={inputCls} />
          </div>
        </div>
        <div>
          <label className="block text-xs text-neutral-500 mb-1">Message (optional)</label>
          <input value={message} onChange={(e) => setMessage(e.target.value)} className={inputCls} />
        </div>
        <div>
          <label className="block text-xs text-neutral-500 mb-1">
            When was this received? (optional — defaults to right now)
          </label>
          <input
            type="datetime-local"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            className={inputCls}
          />
          <p className="text-xs text-neutral-600 mt-1">
            Use this to backdate a real donation to when you actually received it (e.g. a gift given a few days ago).
          </p>
        </div>
        <div className="flex gap-4">
          <label className="flex items-center gap-2 text-xs">
            <input type="checkbox" checked={isRecurring} onChange={(e) => setIsRecurring(e.target.checked)} /> Recurring
          </label>
          <label className="flex items-center gap-2 text-xs">
            <input type="checkbox" checked={isPublic} onChange={(e) => setIsPublic(e.target.checked)} /> Show publicly
          </label>
        </div>
        {error && <p className="text-red-500 text-xs">{error}</p>}
        <button onClick={submit} disabled={saving} className="btn-primary px-5 py-2 text-sm">
          {saving ? "Saving..." : "Add Supporter"}
        </button>
      </div>

      <div className="card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-neutral-900 text-neutral-500 text-left">
            <tr>
              <th className="p-3">Name</th>
              <th className="p-3">Amount</th>
              <th className="p-3">Status</th>
              <th className="p-3">Public</th>
              <th className="p-3">Date</th>
            </tr>
          </thead>
          <tbody>
            {tips.map((t) => (
              <tr key={t.id} className="border-t border-neutral-800">
                <td className="p-3">{t.name}</td>
                <td className="p-3">${(t.realAmount ?? t.amount).toFixed(2)}</td>
                <td className="p-3 capitalize">{t.status}</td>
                <td className="p-3">{t.isPublic ? "Yes" : "No"}</td>
                <td className="p-3 text-neutral-400">{new Date(t.createdAt).toLocaleDateString()}</td>
              </tr>
            ))}
            {tips.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-neutral-500">No supporters yet.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}
