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

type Ride = {
  ride_id: number;
  origin_address: string;
  destination_address: string;
  ride_time: number;
  fare_price: number;
  payment_status: string;
  created_at: string;
  user_email: string;
  driver: { driver_id: number; name: string; rating: number };
};

type RidesResponse = {
  data: Ride[];
  total: number;
  page: number;
  pageSize: number;
  pages: number;
};

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

export default function Rides() {
  const [rides, setRides] = useState<Ride[]>([]);
  const [meta, setMeta] = useState({ total: 0, page: 1, pages: 1 });
  const [status, setStatus] = useState("");
  const [query, setQuery] = useState("");
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async (status: string, q: string, page: number) => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (status) params.set("status", status);
      if (q) params.set("q", q);
      if (page > 1) params.set("page", String(page));
      const res = await api<RidesResponse>(
        `/admin/rides${params.size ? `?${params}` : ""}`,
      );
      setRides(res.data);
      setMeta({ total: res.total, page: res.page, pages: res.pages });
      setError(null);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load(status, query, page);
  }, [load, status, page]);

  const search = () => {
    setPage(1);
    load(status, query, 1);
  };

  return (
    <>
      <h2>Rides & payments</h2>
      <div className="toolbar">
        <input
          placeholder="Search email, driver or address…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && search()}
        />
        <select
          value={status}
          onChange={(e) => {
            setStatus(e.target.value);
            setPage(1);
          }}
        >
          <option value="">All payments</option>
          <option value="paid">Paid</option>
          <option value="unpaid">Unpaid</option>
        </select>
        <button className="secondary" onClick={search}>
          Search
        </button>
        <span className="muted">
          {fmt(meta.total)} ride{meta.total === 1 ? "" : "s"}
        </span>
      </div>

      {error && <div className="error">{error}</div>}
      {!loading && !error && rides.length === 0 && (
        <div className="muted">No rides match the current filters.</div>
      )}

      {rides.length > 0 && (
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Route</th>
              <th>User</th>
              <th>Driver</th>
              <th>Time (min)</th>
              <th>Fare</th>
              <th>Payment</th>
              <th>Date</th>
            </tr>
          </thead>
          <tbody className={loading ? "loading" : ""}>
            {rides.map((r) => (
              <tr key={r.ride_id} style={loading ? { opacity: 0.5 } : undefined}>
                <td>{r.ride_id}</td>
                <td>
                  {r.origin_address} → {r.destination_address}
                </td>
                <td>{r.user_email}</td>
                <td>{r.driver.name}</td>
                <td>{r.ride_time}</td>
                <td>{fmt(r.fare_price)}</td>
                <td>
                  <span
                    className={`badge ${
                      r.payment_status.toLowerCase() === "paid" ? "paid" : "unpaid"
                    }`}
                  >
                    {r.payment_status}
                  </span>
                </td>
                <td>{new Date(r.created_at).toLocaleString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      <div className="toolbar pager">
        <button
          className="secondary"
          disabled={meta.page <= 1 || loading}
          onClick={() => setPage((p) => p - 1)}
        >
          ← Prev
        </button>
        <span className="muted">
          Page {meta.page} of {meta.pages}
        </span>
        <button
          className="secondary"
          disabled={meta.page >= meta.pages || loading}
          onClick={() => setPage((p) => p + 1)}
        >
          Next →
        </button>
      </div>
    </>
  );
}
