"use client";
import { useEffect, useState } from "react";
import Link from "next/link";

export default function AdminRecurringPage() {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/recurring")
      .then((r) => r.json())
      .then((d) => {
        setData(d);
        setLoading(false);
      });
  }, []);

  if (loading) return <p className="text-neutral-500">Loading...</p>;

  return (
    <div>
      <h2 className="text-lg font-semibold mb-1">Recurring Revenue</h2>
      <p className="text-xs text-neutral-500 mb-6">
        Everyone currently on an active recurring membership or recurring tip. This list updates
        automatically the moment someone's subscription actually ends — whether they cancel through
        the site, through Stripe directly, or a renewal charge finally fails for good.
      </p>

      <div className="grid sm:grid-cols-2 gap-4 mb-6">
        <div className="card p-4 bg-gradient-to-br from-purple-950/40 to-transparent border-purple-900/40">
          <p className="text-neutral-400 text-xs mb-1">Recurring Membership Revenue / month</p>
          <p className="text-2xl font-bold">${data.monthlyMembershipTotal.toFixed(2)}</p>
          <p className="text-xs text-neutral-500 mt-1">{data.recurringMembers.length} active member{data.recurringMembers.length === 1 ? "" : "s"}</p>
        </div>
        <div className="card p-4 bg-gradient-to-br from-amber-950/40 to-transparent border-amber-900/40">
          <p className="text-neutral-400 text-xs mb-1">Recurring Tip Revenue / month</p>
          <p className="text-2xl font-bold">${data.monthlyTipTotal.toFixed(2)}</p>
          <p className="text-xs text-neutral-500 mt-1">{data.recurringSupporters.length} recurring supporter{data.recurringSupporters.length === 1 ? "" : "s"}</p>
        </div>
      </div>

      <div className="card overflow-hidden mb-6">
        <div className="p-4 border-b border-neutral-800">
          <h3 className="font-semibold">Recurring Members ({data.recurringMembers.length})</h3>
        </div>
        <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">Email</th><th className="p-3">Tier</th><th className="p-3">Monthly</th><th className="p-3">Renewals</th><th className="p-3">Last Charge</th></tr>
          </thead>
          <tbody>
            {data.recurringMembers.map((m: any) => (
              <tr key={m.userId} className="border-t border-neutral-800">
                <td className="p-3">
                  <Link href={`/profile/${m.userId}`} target="_blank" className="hover:text-red-400">{m.name}</Link>
                </td>
                <td className="p-3 text-neutral-400">{m.email}</td>
                <td className="p-3 capitalize">{m.tier}</td>
                <td className="p-3">${m.amount.toFixed(2)}</td>
                <td className="p-3">{m.renewalCount}</td>
                <td className="p-3 text-neutral-400">{m.lastChargeDate ? new Date(m.lastChargeDate).toLocaleDateString() : "—"}</td>
              </tr>
            ))}
            {data.recurringMembers.length === 0 && (
              <tr><td colSpan={6} className="p-6 text-center text-neutral-500">No active recurring members right now.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="card overflow-hidden">
        <div className="p-4 border-b border-neutral-800">
          <h3 className="font-semibold">Recurring Supporters ({data.recurringSupporters.length})</h3>
        </div>
        <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">Monthly Amount</th><th className="p-3">Last Charge</th></tr>
          </thead>
          <tbody>
            {data.recurringSupporters.map((s: any, i: number) => (
              <tr key={i} className="border-t border-neutral-800">
                <td className="p-3">{s.userId ? <Link href={`/profile/${s.userId}`} target="_blank" className="hover:text-red-400">{s.name}</Link> : s.name}</td>
                <td className="p-3">${s.amount.toFixed(2)}</td>
                <td className="p-3 text-neutral-400">{s.lastChargeDate ? new Date(s.lastChargeDate).toLocaleDateString() : "—"}</td>
              </tr>
            ))}
            {data.recurringSupporters.length === 0 && (
              <tr><td colSpan={3} className="p-6 text-center text-neutral-500">No active recurring supporters right now.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
