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

export default function FailedPaymentsPage() {
  const [records, setRecords] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

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

  // Group by email so the admin can quickly see repeat failures, while
  // still keeping every individual attempt as its own row in the table.
  const failCountByEmail: Record<string, number> = {};
  for (const r of records) {
    if (r.email !== "—") failCountByEmail[r.email] = (failCountByEmail[r.email] || 0) + 1;
  }

  return (
    <div>
      <Link href="/admin/reports" className="text-xs text-neutral-500 hover:text-white">← Back to Reports</Link>
      <h2 className="text-lg font-semibold mt-2 mb-1">Failed Payments</h2>
      <p className="text-xs text-neutral-500 mb-6">
        Every failed attempt, individually — someone who failed twice shows as two separate rows below.
      </p>

      {loading ? (
        <p className="text-neutral-500">Loading...</p>
      ) : records.length === 0 ? (
        <div className="card p-6 text-center text-neutral-500 text-sm">No failed payments recorded.</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">Email</th>
                <th className="p-3">Description</th>
                <th className="p-3">Amount</th>
                <th className="p-3">Reason</th>
                <th className="p-3">Date</th>
              </tr>
            </thead>
            <tbody>
              {records.map((r) => (
                <tr key={r.id} className="border-t border-neutral-800">
                  <td className="p-3">{r.name}</td>
                  <td className="p-3">
                    {r.email}
                    {failCountByEmail[r.email] > 1 && (
                      <span className="ml-2 text-[10px] bg-red-900/50 text-red-400 px-2 py-0.5 rounded-full">
                        {failCountByEmail[r.email]}× failed
                      </span>
                    )}
                  </td>
                  <td className="p-3 max-w-xs truncate">{r.description}</td>
                  <td className="p-3">${r.amount.toFixed(2)}</td>
                  <td className="p-3 text-neutral-400 max-w-xs truncate">{r.reason || "—"}</td>
                  <td className="p-3 text-neutral-400">{r.date ? new Date(r.date).toLocaleString() : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
