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

type Stats = {
  totals: {
    users: number;
    drivers: number;
    rides: number;
    revenue: number;
    rides_today: number;
    avg_fare: number;
    pending_count: number;
    pending_revenue: number;
    new_users_7d: number;
  };
  trend: { day: string; rides: number; revenue: number }[];
  topDrivers: { driver_id: number; name: string; rides: number; revenue: number }[];
};

const fmt = (n: number) => n.toLocaleString();

export default function Stats() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [metric, setMetric] = useState<"rides" | "revenue">("rides");

  useEffect(() => {
    api<{ data: Stats }>("/admin/stats")
      .then((r) => setStats(r.data))
      .catch((e) => setError(e.message));
  }, []);

  if (error) return <div className="error">{error}</div>;
  if (!stats) return <div className="muted">Loading…</div>;

  const t = stats.totals;
  const max = Math.max(1, ...stats.trend.map((d) => d[metric]));

  return (
    <>
      <h2>Overview</h2>
      <div className="cards">
        <div className="card">
          <div className="label">Users</div>
          <div className="value">{fmt(t.users)}</div>
          <div className="sub">+{fmt(t.new_users_7d)} this week</div>
        </div>
        <div className="card">
          <div className="label">Drivers</div>
          <div className="value">{fmt(t.drivers)}</div>
        </div>
        <div className="card">
          <div className="label">Rides</div>
          <div className="value">{fmt(t.rides)}</div>
          <div className="sub">{fmt(t.rides_today)} today</div>
        </div>
        <div className="card">
          <div className="label">Revenue (paid)</div>
          <div className="value">{fmt(t.revenue)}</div>
          <div className="sub">avg fare {fmt(t.avg_fare)}</div>
        </div>
        <div className={`card ${t.pending_count > 0 ? "warn" : ""}`}>
          <div className="label">Pending payments</div>
          <div className="value">{fmt(t.pending_count)}</div>
          <div className="sub">{fmt(t.pending_revenue)} outstanding</div>
        </div>
      </div>

      <h2>Last 14 days</h2>
      <div className="toolbar">
        <select value={metric} onChange={(e) => setMetric(e.target.value as "rides" | "revenue")}>
          <option value="rides">Rides</option>
          <option value="revenue">Revenue (paid)</option>
        </select>
      </div>
      <div className="chart" style={{ marginBottom: 40 }}>
        {stats.trend.map((d) => (
          <div
            key={d.day}
            className="bar"
            style={{ height: `${Math.max(1, (d[metric] / max) * 100)}%` }}
            title={`${d.day}: ${metric === "rides" ? `${d.rides} rides` : fmt(d.revenue)}`}
          >
            <span>{d.day.slice(5)}</span>
          </div>
        ))}
      </div>

      <h2>Top drivers</h2>
      <table>
        <thead>
          <tr>
            <th>Driver</th>
            <th>Rides</th>
            <th>Revenue</th>
          </tr>
        </thead>
        <tbody>
          {stats.topDrivers.map((d) => (
            <tr key={d.driver_id}>
              <td>{d.name}</td>
              <td>{fmt(d.rides)}</td>
              <td>{fmt(d.revenue)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}
