import { useEffect, useState } from 'react';
import api from '../../api/client.js';
import Spinner from '../../components/Spinner.jsx';
import { useToast } from '../../context/ToastContext.jsx';

function money(cents, currency = 'usd') {
  return new Intl.NumberFormat(undefined, {
    style: 'currency',
    currency: currency.toUpperCase(),
  }).format((cents || 0) / 100);
}

const statusBadge = { PAID: 'badge-green', PENDING: 'badge-amber', FAILED: 'badge-red' };

export default function AdminFinance() {
  const toast = useToast();
  const [data, setData] = useState(null);

  useEffect(() => {
    api.get('/payments/admin/finance')
      .then(({ data }) => setData(data))
      .catch((e) => toast.error(e.message));
  }, [toast]);

  if (!data) return <Spinner />;

  const { summary, purchases } = data;

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))' }}>
        <div className="card stat">
          <div className="num">{money(summary.totalRevenueCents, summary.currency)}</div>
          <div className="lbl">Total revenue</div>
        </div>
        <div className="card stat"><div className="num">{summary.paidCount}</div><div className="lbl">Paid orders</div></div>
        <div className="card stat"><div className="num">{summary.pendingCount}</div><div className="lbl">Pending</div></div>
        <div className="card stat"><div className="num">{summary.totalCount}</div><div className="lbl">Total orders</div></div>
      </div>

      {!data.stripeConfigured && (
        <div className="alert mt-3">Stripe is not configured — figures reflect test-mode / dev-grant unlocks.</div>
      )}

      <div className="card table-card mt-3">
        <div className="table-scroll">
        <table className="table">
          <thead>
            <tr><th>Customer</th><th>Exam</th><th>Amount</th><th>Status</th><th>Date</th></tr>
          </thead>
          <tbody>
            {purchases.map((p) => (
              <tr key={p.id}>
                <td>
                  <b>{p.user?.name || '—'}</b>
                  <div className="muted" style={{ fontSize: '0.85rem' }}>{p.user?.email}</div>
                </td>
                <td>{p.course?.title || '—'}</td>
                <td>{money(p.amountCents, p.currency)}</td>
                <td><span className={`badge ${statusBadge[p.status] || ''}`}>{p.status}</span></td>
                <td className="muted">{new Date(p.createdAt).toLocaleDateString()}</td>
              </tr>
            ))}
            {purchases.length === 0 && <tr><td colSpan="5" className="muted">No purchases yet.</td></tr>}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}
