"use client";

import { useParams } from "next/navigation";
import { PageHeader } from "@/components/ui/page-header";
import { Card, InfoRow, TruckSubnav, formatCompactMoney, formatDate, useTruckCommandData } from "../truck-command-support";

export default function TruckHistoryPage() {
  const params = useParams<{ id: string }>();
  const truckId = params?.id;
  const { truck, weeklySummaries, error } = useTruckCommandData(truckId);

  if (error) return <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>;
  if (!truck || !truckId) return <div className="text-sm text-slate-500">Loading history...</div>;

  return (
    <div className="space-y-5">
      <PageHeader title={`Truck ${truck.truckNumber} · History`} subtitle="Review recent weeks for this truck without crowding the main truck page." />
      <TruckSubnav truckId={truckId} />
      <Card title="Recent weekly history" dense>
        <div className="space-y-3">
          {weeklySummaries.length ? weeklySummaries.slice(0, 6).map((week) => (
            <div key={week.weekStartDate} className="rounded-xl border border-slate-200 p-3">
              <div className="mb-2 text-sm font-semibold text-slate-900">Week of {formatDate(week.weekStartDate)}</div>
              <InfoRow label="Revenue" value={formatCompactMoney(week.totalRevenue ?? null)} />
              <InfoRow label="Outstanding" value={formatCompactMoney(week.outstandingRevenue ?? null)} />
              <InfoRow label="Paid" value={formatCompactMoney(week.paidRevenue ?? null)} />
              <InfoRow label="Miles" value={week.totalMiles ?? "0"} />
            </div>
          )) : <div className="text-sm text-slate-600">No weekly history saved yet.</div>}
        </div>
      </Card>
    </div>
  );
}
