import React from "react";
import { useQuery } from "@tanstack/react-query";
import { Truck, Warehouse, ShoppingBag, AlertTriangle } from "lucide-react";
import { DashboardMultiStatCardMini } from "@/components/dashboard/shared";
import { acotService } from "@/services/dashboard/acotService";
import config from "@/config";
import { apiFetch } from "@/utils/api";

const fmtCurrency = (value) => {
  if (!value && value !== 0) return "$0";
  if (value >= 1000000) return `$${(value / 1000000).toFixed(1)}M`;
  if (value >= 1000) return `$${(value / 1000).toFixed(0)}K`;
  return `$${value.toFixed(0)}`;
};

const fmtNum = (value) => {
  if (!value && value !== 0) return "0";
  if (value >= 1000) return `${(value / 1000).toFixed(1)}K`;
  return value.toLocaleString();
};

const MiniInventorySnapshot = () => {
  // Operations (shipped/picked today)
  const { data: opsData, isLoading: opsLoading } = useQuery({
    queryKey: ["mini-ops-today"],
    queryFn: () => acotService.getOperationsMetrics({ timeRange: "today" }),
    refetchInterval: 120000,
  });

  // Stock metrics
  const { data: stockData, isLoading: stockLoading } = useQuery({
    queryKey: ["mini-stock-metrics"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/stock/metrics`);
      if (!response.ok) throw new Error("Failed to fetch stock metrics");
      return response.json();
    },
    refetchInterval: 300000,
  });

  // Replenishment metrics
  const { data: replenishData, isLoading: replenishLoading } = useQuery({
    queryKey: ["mini-replenish-metrics"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/replenishment/metrics`);
      if (!response.ok) throw new Error("Failed to fetch replenishment");
      return response.json();
    },
    refetchInterval: 300000,
  });

  // Overstock metrics
  const { data: overstockData, isLoading: overstockLoading } = useQuery({
    queryKey: ["mini-overstock-metrics"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/overstock/metrics`);
      if (!response.ok) throw new Error("Failed to fetch overstock");
      return response.json();
    },
    refetchInterval: 300000,
  });

  const loading = opsLoading || stockLoading || replenishLoading || overstockLoading;
  const ready = !loading && opsData?.totals && stockData && replenishData && overstockData;

  const t = opsData?.totals;

  const entries = ready
    ? [
        {
          icon: Truck,
          iconBg: "bg-sky-400",
          label: "Shipped",
          value: `${fmtNum(t.ordersShipped)}`,
          sub: `${fmtNum(t.piecesPicked)} pcs picked`,
        },
        {
          icon: Warehouse,
          iconBg: "bg-emerald-400",
          label: "Stock Value",
          value: fmtCurrency(stockData.totalStockCost),
          sub: `${fmtNum(stockData.productsInStock)} products`,
        },
        {
          icon: ShoppingBag,
          iconBg: "bg-amber-400",
          label: "Replenish Units",
          value: `${fmtNum(replenishData.unitsToReplenish)}`,
          sub: `${fmtCurrency(replenishData.replenishmentCost)} cost`,
        },
        {
          icon: AlertTriangle,
          iconBg: overstockData.overstockedProducts > 0 ? "bg-rose-400" : "bg-violet-400",
          label: "Overstocked SKUs",
          value: `${fmtNum(overstockData.overstockedProducts)}`,
          sub: `${fmtCurrency(overstockData.totalExcessCost)} cost`,
        },
      ]
    : [];

  return (
    <DashboardMultiStatCardMini
      title="Today"
      entries={entries}
      gradient="amber"
      loading={!ready}
      skeletonRows={4}
    />
  );
};

export default MiniInventorySnapshot;
