import { formatMoney } from "@/lib/format";

// Pre-formatted delta chip from the API (don't recompute percentages).
export interface Change {
  formatted: string;
  trend: "up" | "down";
  label: string;
}

// `cards` payload from provider/home.
export interface HomeCards {
  trips_today: { value: number; avg_per_vehicle: number };
  revenue_today: { value: number; your_share: number; change: Change };
  vehicles: {
    total: number;
    active: number;
    maintenance: number;
    in_ride: number;
    inactive: number;
  };
  total_profits: { value: number; change: Change };
}

interface CardView {
  icon: string;
  label: string;
  value: string;
  sub: string;
  subColor: string;
  subIcon: string | null;
}

export default function SummaryCards({
  cards,
  currency,
}: Readonly<{
  cards: HomeCards;
  currency: string;
}>) {
  // Map a pre-formatted change into the existing chip styling.
  const chip = (c: Change) => ({
    sub: `${c.formatted} ${c.label}`,
    subColor: c.trend === "down" ? "text-red-400" : "text-[#FCD704]",
    subIcon: c.trend === "down" ? "ri-arrow-down-line" : "ri-arrow-up-line",
  });

  // Same four KPI cards, same order/markup — now sourced from the response.
  const items: CardView[] = [
    {
      icon: "ri-copper-coin-line",
      label: "إجمالي الأرباح",
      value: formatMoney(cards.total_profits.value, currency),
      ...chip(cards.total_profits.change),
    },
    {
      icon: "ri-e-bike-line",
      label: "مركباتي",
      value: `${cards.vehicles.total} مركبات`,
      sub: `${cards.vehicles.active} نشطة · ${cards.vehicles.maintenance} صيانة`,
      subColor: "text-gray-400",
      subIcon: null,
    },
    {
      icon: "ri-bar-chart-2-line",
      label: "إيرادات اليوم",
      value: formatMoney(cards.revenue_today.value, currency),
      ...chip(cards.revenue_today.change),
    },
    {
      icon: "ri-route-line",
      label: "الرحلات اليوم",
      value: `${cards.trips_today.value} رحلة`,
      sub: `متوسط ${cards.trips_today.avg_per_vehicle} رحلة/مركبة`,
      subColor: "text-gray-400",
      subIcon: null,
    },
  ];

  return (
    <div className="grid grid-cols-4 gap-5">
      {items.map((c) => (
        <div key={c.label} className="bg-[#1E2128] rounded-2xl p-5">
          <div className="flex items-center justify-between mb-4">
            <div className={`text-xs ${c.subColor} flex items-center gap-1`}>
              {c.subIcon && <i className={`${c.subIcon} text-xs`} />}
              {c.sub}
            </div>
            <div className="w-10 h-10 bg-[#FCD704]/15 rounded-xl flex items-center justify-center">
              <i className={`${c.icon} text-[#FCD704] text-xl`} />
            </div>
          </div>
          <p className="text-white font-black text-2xl text-right">{c.value}</p>
          <p className="text-gray-400 text-xs text-right mt-1">{c.label}</p>
        </div>
      ))}
    </div>
  );
}
