import { useEffect, useState } from "react";
import { api } from "../api.js";

interface Sub {
  id: string;
  userId: string;
  provider: string;
  plan: string;
  status: string;
  expiresAt: string | null;
  lastVerifiedAt: string | null;
}

export function SubscriptionsPage() {
  const [subs, setSubs] = useState<Sub[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    api<{ subscriptions: Sub[] }>("/admin/v1/subscriptions")
      .then((r) => setSubs(r.subscriptions))
      .catch((e) => setError(String(e.message)));
  }, []);

  const statusBadge = (status: string) =>
    status === "active" || status === "trial" ? "ok" : status === "in_grace" ? "warn" : "err";

  return (
    <div>
      <h2>Prenumerationer</h2>
      <p className="muted">
        Backend är source of truth (spec §47). Promo-planer delas ut via API:t.
      </p>
      {error && <div className="error-text">{error}</div>}
      <div className="panel">
        <table>
          <thead>
            <tr>
              <th>Användare</th>
              <th>Plan</th>
              <th>Provider</th>
              <th>Status</th>
              <th>Går ut</th>
              <th>Senast verifierad</th>
            </tr>
          </thead>
          <tbody>
            {subs.map((s) => (
              <tr key={s.id}>
                <td>
                  <code>{s.userId.slice(0, 8)}…</code>
                </td>
                <td>{s.plan}</td>
                <td>{s.provider}</td>
                <td>
                  <span className={`badge ${statusBadge(s.status)}`}>{s.status}</span>
                </td>
                <td>{s.expiresAt ? new Date(s.expiresAt).toLocaleDateString("sv-SE") : "–"}</td>
                <td>
                  {s.lastVerifiedAt ? new Date(s.lastVerifiedAt).toLocaleString("sv-SE") : "–"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
