'use client';

import { useState, useEffect } from 'react';
import { ShoppingBag, TrendingUp, AlertTriangle, CheckCircle2, Clock, Zap } from 'lucide-react';
import { getOrderStats, type OrderStats } from '@client/api/orders';
import { useCurrency } from '@client/hooks/useCurrency';
import { useLanguage } from '@client/contexts/LanguageContext';
import type React from 'react';

interface SummaryStat {
  label: string;
  value: string;
  sub: string;
  icon: React.ReactNode;
  iconBg: string;
  iconColor: string;
  positive: boolean;
}

function buildStats(s: OrderStats, fc: (n: number) => string, t: (key: string, fallback: string) => string): SummaryStat[] {
  const completionRate = s.totalOrders > 0 ? ((s.completedOrders / s.totalOrders) * 100).toFixed(1) : '0';
  return [
    { label: t('orderManagement.totalOrders', 'Total Orders'), value: String(s.totalOrders), sub: t('orderManagement.totalOrdersSub', '{count} orders total').replace('{count}', String(s.totalOrders)), icon: <ShoppingBag size={16} />, iconBg: 'hsl(var(--primary-light))', iconColor: 'hsl(var(--primary))', positive: true },
    { label: t('orderManagement.revenue', 'Revenue'), value: fc(s.totalRevenue), sub: t('orderManagement.revenueSub', 'From completed orders'), icon: <TrendingUp size={16} />, iconBg: 'hsl(var(--success-bg))', iconColor: 'hsl(var(--success))', positive: true },
    { label: t('orderManagement.pending', 'Pending'), value: String(s.pendingOrders), sub: t('orderManagement.pendingSub', '{count} awaiting action').replace('{count}', String(s.pendingOrders)), icon: <Clock size={16} />, iconBg: 'hsl(var(--warning-bg))', iconColor: 'hsl(var(--warning))', positive: s.pendingOrders === 0 },
    { label: t('orderManagement.cancelled', 'Cancelled'), value: String(s.cancelledOrders), sub: t('orderManagement.cancelledSub', '{count} cancelled').replace('{count}', String(s.cancelledOrders)), icon: <AlertTriangle size={16} />, iconBg: 'hsl(var(--danger-bg))', iconColor: 'hsl(var(--danger))', positive: s.cancelledOrders === 0 },
    { label: t('orderManagement.completed', 'Completed'), value: String(s.completedOrders), sub: t('orderManagement.completedSub', '{rate}% completion rate').replace('{rate}', completionRate), icon: <CheckCircle2 size={16} />, iconBg: 'hsl(var(--success-bg))', iconColor: 'hsl(var(--success))', positive: true },
    { label: t('orderManagement.completionRate', 'Completion Rate'), value: `${completionRate}%`, sub: t('orderManagement.completionRateSub', 'Of all orders'), icon: <Zap size={16} />, iconBg: 'hsl(var(--info-bg))', iconColor: 'hsl(var(--info))', positive: true },
  ];
}

export default function OrderSummaryStrip() {
  const { format: fc } = useCurrency();
  const { t } = useLanguage();
  const [stats, setStats] = useState<OrderStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getOrderStats()
      .then(res => setStats(res.stats))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading || !stats) {
    return (
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 xl:grid-cols-6 2xl:grid-cols-6 gap-3 mb-5">
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i} className="card px-4 py-3 flex items-center gap-3 animate-pulse">
            <div className="w-8 h-8 rounded-lg bg-gray-200" />
            <div>
              <div className="h-3 w-16 bg-gray-200 rounded mb-1" />
              <div className="h-5 w-10 bg-gray-200 rounded" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  const items = buildStats(stats, fc, t);

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 xl:grid-cols-6 2xl:grid-cols-6 gap-3 mb-5">
      {items.map(stat => (
        <div key={stat.label} className="card px-4 py-3 flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: stat.iconBg, color: stat.iconColor }}>
            {stat.icon}
          </div>
          <div className="min-w-0">
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
            <p className="text-base font-bold font-mono tabular-nums leading-tight" style={{ color: 'hsl(var(--foreground))' }}>{stat.value}</p>
            <p className="text-xs" style={{ color: stat.positive ? 'hsl(var(--success))' : 'hsl(var(--danger))' }}>{stat.sub}</p>
          </div>
        </div>
      ))}
    </div>
  );
}
