import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/utils/api';
import {
  DollarSign,
  Package,
  AlertTriangle,
  Clock,
  PackageX,
  PackageMinus,
  Truck,
  ShoppingCart,
} from 'lucide-react';

interface SummaryData {
  total_products: number;
  total_stock_value: string;
  total_stock_retail: string;
  needs_reorder_count: number;
  total_replenishment_cost: string;
  total_replenishment_units: number;
  total_overstock_value: string;
  total_overstock_units: number;
  total_on_order_units: number;
  total_on_order_cost: string;
  avg_stock_cover_days: string;
  out_of_stock_count: number;
  total_lost_revenue: string;
  total_lost_sales_units: number;
  critical_count: number;
  reorder_count: number;
  at_risk_count: number;
  overstock_count: number;
  healthy_count: number;
  new_count: number;
}

interface ProductSummaryCardsProps {
  activeView: string;
  showNonReplenishable: boolean;
  showInvisible: boolean;
}

function formatCurrency(value: string | number): string {
  const num = typeof value === 'string' ? parseFloat(value) : value;
  if (isNaN(num)) return '$0';
  if (num >= 1_000_000) return `$${(num / 1_000_000).toFixed(1)}M`;
  if (num >= 1_000) return `$${(num / 1_000).toFixed(1)}K`;
  return `$${num.toFixed(0)}`;
}

function formatNumber(value: number): string {
  return value.toLocaleString();
}

function formatDays(value: string | number): string {
  const num = typeof value === 'string' ? parseFloat(value) : value;
  if (isNaN(num) || num === 0) return '0 days';
  return `${num.toFixed(0)} days`;
}

interface CardConfig {
  label: string;
  value: string;
  subValue?: string;
  icon: any;
  iconClassName: string;
}

function getCardsForView(data: SummaryData, activeView: string): CardConfig[] {
  const allCards: Record<string, CardConfig[]> = {
    all: [
      {
        label: 'Stock Value',
        value: formatCurrency(data.total_stock_value),
        subValue: `${formatCurrency(data.total_stock_retail)} retail`,
        icon: DollarSign,
        iconClassName: 'text-blue-500',
      },
      {
        label: 'Needs Reorder',
        value: formatNumber(data.needs_reorder_count),
        subValue: `${formatCurrency(data.total_replenishment_cost)} to replenish`,
        icon: AlertTriangle,
        iconClassName: 'text-amber-500',
      },
      {
        label: 'On Order',
        value: formatNumber(data.total_on_order_units) + ' units',
        subValue: `${formatCurrency(data.total_on_order_cost)} cost`,
        icon: Truck,
        iconClassName: 'text-indigo-500',
      },
      {
        label: 'Overstock Value',
        value: formatCurrency(data.total_overstock_value),
        subValue: `${formatNumber(data.total_overstock_units)} excess units`,
        icon: PackageX,
        iconClassName: 'text-orange-400',
      },
    ],
    critical: [
      {
        label: 'Out of Stock',
        value: formatNumber(data.out_of_stock_count),
        subValue: `of ${formatNumber(data.total_products)} products`,
        icon: PackageMinus,
        iconClassName: 'text-red-500',
      },
      {
        label: 'Replenishment Needed',
        value: formatNumber(data.total_replenishment_units) + ' units',
        subValue: `${formatCurrency(data.total_replenishment_cost)} cost`,
        icon: ShoppingCart,
        iconClassName: 'text-blue-500',
      },
      {
        label: 'On Order',
        value: formatNumber(data.total_on_order_units) + ' units',
        subValue: `${formatCurrency(data.total_on_order_cost)} cost`,
        icon: Truck,
        iconClassName: 'text-indigo-500',
      },
      {
        label: 'Forecast Lost Sales',
        value: formatNumber(data.total_lost_sales_units) + ' units',
        subValue: `${formatCurrency(data.total_lost_revenue)} revenue`,
        icon: AlertTriangle,
        iconClassName: 'text-red-400',
      },
    ],
    reorder: [
      {
        label: 'Replenishment Needed',
        value: formatNumber(data.total_replenishment_units) + ' units',
        subValue: `${formatCurrency(data.total_replenishment_cost)} cost`,
        icon: ShoppingCart,
        iconClassName: 'text-amber-500',
      },
      {
        label: 'Also Critical',
        value: formatNumber(data.critical_count),
        subValue: 'need ordering too',
        icon: AlertTriangle,
        iconClassName: 'text-red-500',
      },
      {
        label: 'On Order',
        value: formatNumber(data.total_on_order_units) + ' units',
        subValue: `${formatCurrency(data.total_on_order_cost)} cost`,
        icon: Truck,
        iconClassName: 'text-indigo-500',
      },
      {
        label: 'Forecast Lost Sales',
        value: formatNumber(data.total_lost_sales_units) + ' units',
        subValue: `${formatCurrency(data.total_lost_revenue)} revenue`,
        icon: AlertTriangle,
        iconClassName: 'text-red-400',
      },
    ],
    healthy: [
      {
        label: 'Healthy Products',
        value: formatNumber(data.healthy_count),
        subValue: `of ${formatNumber(data.total_products)} total`,
        icon: Package,
        iconClassName: 'text-green-500',
      },
      {
        label: 'Avg Stock Cover',
        value: formatDays(data.avg_stock_cover_days),
        icon: Clock,
        iconClassName: 'text-green-500',
      },
      {
        label: 'Stock Value',
        value: formatCurrency(data.total_stock_value),
        subValue: `${formatCurrency(data.total_stock_retail)} retail`,
        icon: DollarSign,
        iconClassName: 'text-blue-500',
      },
      {
        label: 'On Order',
        value: formatNumber(data.total_on_order_units) + ' units',
        subValue: `${formatCurrency(data.total_on_order_cost)} cost`,
        icon: Truck,
        iconClassName: 'text-indigo-500',
      },
    ],
    'at-risk': [
      {
        label: 'At Risk Products',
        value: formatNumber(data.at_risk_count),
        icon: AlertTriangle,
        iconClassName: 'text-orange-500',
      },
      {
        label: 'Avg Stock Cover',
        value: formatDays(data.avg_stock_cover_days),
        icon: Clock,
        iconClassName: 'text-orange-400',
      },
      {
        label: 'Forecast Lost Sales',
        value: formatNumber(data.total_lost_sales_units) + ' units',
        subValue: `${formatCurrency(data.total_lost_revenue)} revenue`,
        icon: AlertTriangle,
        iconClassName: 'text-red-400',
      },
      {
        label: 'On Order',
        value: formatNumber(data.total_on_order_units) + ' units',
        subValue: `${formatCurrency(data.total_on_order_cost)} cost`,
        icon: Truck,
        iconClassName: 'text-indigo-500',
      },
    ],
    overstocked: [
      {
        label: 'Overstocked Products',
        value: formatNumber(data.overstock_count),
        icon: PackageX,
        iconClassName: 'text-orange-400',
      },
      {
        label: 'Excess Units',
        value: formatNumber(data.total_overstock_units),
        icon: Package,
        iconClassName: 'text-orange-400',
      },
      {
        label: 'Overstock Value',
        value: formatCurrency(data.total_overstock_value),
        subValue: 'at cost',
        icon: DollarSign,
        iconClassName: 'text-orange-500',
      },
      {
        label: 'Avg Stock Cover',
        value: formatDays(data.avg_stock_cover_days),
        icon: Clock,
        iconClassName: 'text-blue-400',
      },
    ],
    new: [
      {
        label: 'New Products',
        value: formatNumber(data.new_count),
        icon: Package,
        iconClassName: 'text-purple-500',
      },
      {
        label: 'Stock Value',
        value: formatCurrency(data.total_stock_value),
        subValue: `${formatCurrency(data.total_stock_retail)} retail`,
        icon: DollarSign,
        iconClassName: 'text-blue-500',
      },
      {
        label: 'On Order',
        value: formatNumber(data.total_on_order_units) + ' units',
        subValue: `${formatCurrency(data.total_on_order_cost)} cost`,
        icon: Truck,
        iconClassName: 'text-indigo-500',
      },
      {
        label: 'Out of Stock',
        value: formatNumber(data.out_of_stock_count),
        subValue: `of ${formatNumber(data.total_products)} products`,
        icon: PackageMinus,
        iconClassName: 'text-red-400',
      },
    ],
  };

  return allCards[activeView] || allCards.all;
}

export function ProductSummaryCards({ activeView, showNonReplenishable, showInvisible }: ProductSummaryCardsProps) {
  const { data, isLoading } = useQuery<SummaryData>({
    queryKey: ['productsSummary', showNonReplenishable, showInvisible],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (showNonReplenishable) params.append('showNonReplenishable', 'true');
      if (showInvisible) params.append('showInvisible', 'true');
      const response = await apiFetch(`/api/metrics/summary?${params.toString()}`, { credentials: 'include' });
      if (!response.ok) throw new Error('Failed to fetch summary');
      return response.json();
    },
    staleTime: 60 * 1000, // Cache for 1 minute
  });

  if (isLoading || !data) {
    return (
      <div className="grid grid-cols-4 gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i} className="rounded-lg border bg-card p-4 animate-pulse">
            <div className="h-4 w-24 bg-muted rounded mb-2" />
            <div className="h-7 w-20 bg-muted rounded" />
          </div>
        ))}
      </div>
    );
  }

  const cards = getCardsForView(data, activeView);

  return (
    <div className="grid grid-cols-4 gap-4">
      {cards.map((card) => (
        <div key={card.label} className="rounded-lg border bg-card p-4">
          <div className="flex items-center justify-between">
            <p className="text-sm text-muted-foreground">{card.label}</p>
            <card.icon className={`h-4 w-4 ${card.iconClassName}`} />
          </div>
          <p className="text-2xl font-bold mt-1">{card.value}</p>
          {card.subValue && (
            <p className="text-xs text-muted-foreground mt-0.5">{card.subValue}</p>
          )}
        </div>
      ))}
    </div>
  );
}
