"use client";

import { api, OwnedVehicle } from "@/lib/api";
import { useApi } from "@/hooks/useApi";
import { useSession } from "@/session/SessionProvider";
import { useLocale } from "@/i18n/LocaleProvider";
import {
  EmptyState,
  ErrorState,
  MoneyText,
  Numeric,
  PageHeader,
  SkeletonTable,
  StatTile,
  StatusBadge,
  Tone,
} from "@/components/ui";

/** Condition → tone. The label is always shown, so colour never carries the meaning alone. */
const statusTone: Record<string, Tone> = {
  AVAILABLE: "success",
  IN_USE: "info",
  LOW_BATTERY: "warning",
  MAINTENANCE: "warning",
  OFFLINE: "neutral",
};

export default function Page() {
  const { t } = useLocale();
  const { investorId } = useSession();
  const state = useApi<OwnedVehicle[]>(
    () => api.vehicles(investorId!),
    [investorId],
  );

  const vehicles = state.data ?? [];
  const totalRevenue = vehicles.reduce((sum, v) => sum + v.totalEarnings, 0);
  const totalRides = vehicles.reduce((sum, v) => sum + v.rides, 0);
  const currency = vehicles[0]?.currency ?? "SAR";
  const earning = vehicles.filter((v) => v.rides > 0).length;

  return (
    <div>
      <PageHeader titleKey="nav.vehicles" />

      {state.loading ? (
        <SkeletonTable rows={5} />
      ) : state.error ? (
        <ErrorState onRetry={state.reload} />
      ) : vehicles.length === 0 ? (
        <EmptyState
          icon={<span className="text-xl">🛴</span>}
          title={t("vehicles.emptyTitle")}
          description={t("vehicles.emptyBody")}
        />
      ) : (
        <div className="space-y-6">
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <StatTile
              label={t("vehicles.statOwned")}
              value={vehicles.length}
              tone="brand"
            />
            <StatTile
              label={t("vehicles.statEarning")}
              value={earning}
              tone="success"
            />
            <StatTile label={t("vehicles.statRides")} value={totalRides} tone="info" />
            <StatTile
              label={t("vehicles.statRevenue")}
              value={totalRevenue.toFixed(2)}
              tone="brand"
            />
          </div>

          <div className="card overflow-x-auto">
            <table className="w-full min-w-[720px] text-sm">
              <thead>
                <tr className="border-b border-line">
                  <Th>{t("vehicles.colVehicle")}</Th>
                  <Th>{t("vehicles.colStatus")}</Th>
                  <Th>{t("vehicles.colBattery")}</Th>
                  <Th>{t("vehicles.colRides")}</Th>
                  <Th>{t("vehicles.colRevenue")}</Th>
                  <Th>{t("vehicles.colSince")}</Th>
                </tr>
              </thead>
              <tbody>
                {vehicles.map((v) => (
                  <tr key={v.scooterId} className="border-b border-line last:border-b-0">
                    <td className="px-4 py-3">
                      <div className="font-medium">{v.qrCode ?? v.scooterId.slice(0, 8)}</div>
                      <div className="text-xs text-muted">
                        {[v.vehicleType, v.model].filter(Boolean).join(" · ") || "-"}
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      {v.status ? (
                        <StatusBadge tone={statusTone[v.status] ?? "neutral"}>
                          {v.status}
                        </StatusBadge>
                      ) : (
                        // Fleet was unreachable, say so rather than implying it's offline.
                        <span className="text-xs text-muted-dim">{t("vehicles.noStatus")}</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      {v.batteryPercent == null ? (
                        <span className="text-muted">-</span>
                      ) : (
                        <>
                          <Numeric>{v.batteryPercent}</Numeric>%
                        </>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <Numeric>{v.rides}</Numeric>
                    </td>
                    <td className="px-4 py-3">
                      <MoneyText amount={v.totalEarnings} currency={v.currency} />
                    </td>
                    <td className="px-4 py-3 text-xs text-muted">
                      {new Date(v.assignedAt).toLocaleDateString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <p className="text-xs text-muted">{t("vehicles.privacyNote")}</p>
        </div>
      )}
    </div>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th className="px-4 py-3 text-start text-[11px] font-semibold uppercase tracking-wider text-muted">
      {children}
    </th>
  );
}
