"use client";

import { Bike, Car, CarFront, Truck, Warehouse } from "lucide-react";
import { useDashboardStats } from "@/features/dashboard/overview-data";
import { useI18n, useT } from "@/i18n";
import { formatNumber } from "@/lib/format";
import { useAnimatedNumber } from "./shared";
import type { VehicleTypeValue } from "@/types/dashboard";

/** Vehicle kinds, shown in the order they matter to a delivery fleet. */
const TYPE_ORDER: { key: VehicleTypeValue; icon: typeof Car }[] = [
  { key: "motorcycle", icon: Bike },
  { key: "car", icon: Car },
  { key: "van", icon: CarFront },
  { key: "pickup_truck", icon: Warehouse },
  { key: "truck", icon: Truck },
];

const TYPE_BARS: Record<VehicleTypeValue, string> = {
  motorcycle: "bg-indigo-500",
  car: "bg-primary",
  van: "bg-accent",
  pickup_truck: "bg-warning",
  truck: "bg-success",
};

function TypeCard({ type, count, total }: { type: VehicleTypeValue; count: number; total: number }) {
  const t = useT();
  const { locale } = useI18n();
  const { icon: Icon } = TYPE_ORDER.find((entry) => entry.key === type) ?? { icon: Car };
  const animated = useAnimatedNumber(count);
  const share = total > 0 ? Math.min(100, (count / total) * 100) : 0;

  return (
    <li className="rounded-lg border bg-surface p-2.5">
      <div className="flex items-center justify-between gap-1">
        <span className="min-w-0">
          <Icon className="h-4 w-4 text-muted-foreground" aria-hidden />
          <span className="mt-1 block truncate text-[11px] text-muted-foreground">{t(`widgets.vehicleType.${type}`)}</span>
        </span>
        <span className="numeric shrink-0 text-sm font-bold text-foreground">{formatNumber(animated, locale)}</span>
      </div>
      <div className="mt-2 h-1 w-full overflow-hidden rounded-full bg-muted" dir="ltr">
        <span className={`block h-full rounded-full transition-[width] duration-500 ${TYPE_BARS[type]}`} style={{ width: `${share}%` }} />
      </div>
    </li>
  );
}

export function FleetTypesWidget() {
  const t = useT();
  const { data } = useDashboardStats();

  const byType = data?.vehicles.by_type ?? { motorcycle: 0, car: 0, van: 0, pickup_truck: 0, truck: 0 };
  const total = TYPE_ORDER.reduce((sum, { key }) => sum + (byType[key] ?? 0), 0);

  return (
    <div>
      <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t("widgets.fleetTypes.title")}</p>
      <ul className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-3">
        {TYPE_ORDER.map(({ key }) => (
          <TypeCard key={key} type={key} count={byType[key] ?? 0} total={total} />
        ))}
      </ul>
    </div>
  );
}