import React, { useState, useMemo, useRef } from 'react';
import { Link } from 'react-router-dom';
import { AreaChart, Area, BarChart, Bar, LineChart, Line, ComposedChart, PieChart, Pie, Cell, Sector, Label, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { TrendingUp, TrendingDown, ShoppingCart, DollarSign, Package, Users, AlertTriangle, ArrowUpRight } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { formatMoney, getStoreCurrency } from '@/lib/currency';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useDashboardPeriod } from '@/hooks/useDashboardPeriod';
import { useOverviewAnalytics } from '@/hooks/useAnalytics';
import { LoadingState } from '@/components/LoadingState';
import { ErrorCard } from '@/components/ErrorCard';
import { getPageLoadErrorMessage } from '@/lib/errorHandling';
import { useFABConfig } from '@/hooks/useFABConfig';

// Dummy data for visualization
const DUMMY_DATA = {
  // Key metrics
  metrics: {
    revenue: {
      today: 15750000,
      yesterday: 13200000,
      change: 19.3,
    },
    orders: {
      today: 47,
      yesterday: 42,
      change: 11.9,
      breakdown: {
        completed: 28,
        processing: 12,
        pending: 5,
        failed: 2,
      },
    },
    averageOrderValue: {
      today: 335106,
      yesterday: 314285,
      change: 6.6,
    },
    conversionRate: {
      today: 3.2,
      yesterday: 2.8,
      change: 14.3,
    },
  },

  // Sales chart data (last 30 days)
  salesChart: [
    { date: 'Oct 1', revenue: 8500000, orders: 32 },
    { date: 'Oct 2', revenue: 9200000, orders: 35 },
    { date: 'Oct 3', revenue: 7800000, orders: 28 },
    { date: 'Oct 4', revenue: 11200000, orders: 42 },
    { date: 'Oct 5', revenue: 10500000, orders: 38 },
    { date: 'Oct 6', revenue: 9800000, orders: 36 },
    { date: 'Oct 7', revenue: 12500000, orders: 45 },
    { date: 'Oct 8', revenue: 8900000, orders: 31 },
    { date: 'Oct 9', revenue: 10200000, orders: 37 },
    { date: 'Oct 10', revenue: 11800000, orders: 43 },
    { date: 'Oct 11', revenue: 9500000, orders: 34 },
    { date: 'Oct 12', revenue: 10800000, orders: 39 },
    { date: 'Oct 13', revenue: 12200000, orders: 44 },
    { date: 'Oct 14', revenue: 13500000, orders: 48 },
    { date: 'Oct 15', revenue: 11200000, orders: 40 },
    { date: 'Oct 16', revenue: 10500000, orders: 38 },
    { date: 'Oct 17', revenue: 9800000, orders: 35 },
    { date: 'Oct 18', revenue: 11500000, orders: 41 },
    { date: 'Oct 19', revenue: 12800000, orders: 46 },
    { date: 'Oct 20', revenue: 10200000, orders: 37 },
    { date: 'Oct 21', revenue: 11800000, orders: 42 },
    { date: 'Oct 22', revenue: 13200000, orders: 47 },
    { date: 'Oct 23', revenue: 12500000, orders: 45 },
    { date: 'Oct 24', revenue: 11200000, orders: 40 },
    { date: 'Oct 25', revenue: 14200000, orders: 51 },
    { date: 'Oct 26', revenue: 13800000, orders: 49 },
    { date: 'Oct 27', revenue: 12200000, orders: 44 },
    { date: 'Oct 28', revenue: 13200000, orders: 47 },
    { date: 'Oct 29', revenue: 15750000, orders: 56 },
    { date: 'Oct 30', revenue: 14500000, orders: 52 },
  ],

  // Top products
  topProducts: [
    { id: 1, name: 'Wireless Headphones Pro', quantity: 24, revenue: 7200000, image: '🎧' },
    { id: 2, name: 'Smart Watch Series 5', quantity: 18, revenue: 5400000, image: '⌚' },
    { id: 3, name: 'USB-C Hub 7-in-1', quantity: 32, revenue: 3200000, image: '🔌' },
    { id: 4, name: 'Mechanical Keyboard RGB', quantity: 15, revenue: 2250000, image: '⌨️' },
    { id: 5, name: 'Wireless Mouse Gaming', quantity: 28, revenue: 1680000, image: '🖱️' },
  ],

  // Recent orders
  recentOrders: [
    { id: 87, customer: 'Dwindi Ramadhana', status: 'completed', total: 437000, time: '2 hours ago' },
    { id: 86, customer: 'Budi Santoso', status: 'pending', total: 285000, time: '3 hours ago' },
    { id: 84, customer: 'Siti Nurhaliza', status: 'pending', total: 520000, time: '3 hours ago' },
    { id: 83, customer: 'Ahmad Yani', status: 'pending', total: 175000, time: '3 hours ago' },
    { id: 80, customer: 'Rina Wijaya', status: 'pending', total: 890000, time: '4 hours ago' },
  ],

  // Low stock alerts
  lowStock: [
    { id: 12, name: 'Wireless Headphones Pro', stock: 3, threshold: 10, status: 'critical' },
    { id: 24, name: 'Phone Case Premium', stock: 5, threshold: 15, status: 'low' },
    { id: 35, name: 'Screen Protector Glass', stock: 8, threshold: 20, status: 'low' },
    { id: 48, name: 'Power Bank 20000mAh', stock: 4, threshold: 10, status: 'critical' },
  ],

  // Top customers
  topCustomers: [
    { id: 15, name: 'Dwindi Ramadhana', orders: 12, totalSpent: 8750000 },
    { id: 28, name: 'Budi Santoso', orders: 8, totalSpent: 5200000 },
    { id: 42, name: 'Siti Nurhaliza', orders: 10, totalSpent: 4850000 },
    { id: 56, name: 'Ahmad Yani', orders: 7, totalSpent: 3920000 },
    { id: 63, name: 'Rina Wijaya', orders: 6, totalSpent: 3150000 },
  ],

  // Order status distribution
  orderStatusDistribution: [
    { name: 'Completed', value: 156, color: '#10b981' },
    { name: 'Processing', value: 42, color: '#3b82f6' },
    { name: 'Pending', value: 28, color: '#f59e0b' },
    { name: 'Cancelled', value: 8, color: '#6b7280' },
    { name: 'Failed', value: 5, color: '#ef4444' },
  ],
};

// Metric card component
function MetricCard({ title, value, change, icon: Icon, format = 'number', period }: any) {
  const safeValue = value ?? 0;
  const formattedValue = format === 'money' ? formatMoney(safeValue) : format === 'percent' ? `${safeValue.toFixed(2)}%` : safeValue.toLocaleString();
  
  // Don't show comparison for "All Time"
  const showComparison = change !== undefined && period !== 'all';
  const isPositive = change >= 0;
  
  // Period comparison text
  const periodText = period === '7' ? __('vs previous 7 days') : 
                     period === '14' ? __('vs previous 14 days') : 
                     period === '30' ? __('vs previous 30 days') : '';

  return (
    <div className="rounded-lg border bg-card p-6">
      <div className="flex items-center justify-between mb-4">
        <div className="text-sm font-medium text-muted-foreground">{title}</div>
        <Icon className="w-4 h-4 text-muted-foreground" />
      </div>
      <div className="space-y-1">
        <div className="text-2xl font-bold">{formattedValue}</div>
        {showComparison && (
          <div className={`flex items-center text-xs ${isPositive ? 'text-green-600' : 'text-red-600'}`}>
            {isPositive ? <TrendingUp className="w-3 h-3 mr-1" /> : <TrendingDown className="w-3 h-3 mr-1" />}
            {Math.abs(change).toFixed(1)}% {periodText}
          </div>
        )}
      </div>
    </div>
  );
}


export default function Dashboard() {
  useFABConfig('dashboard'); // Add FAB for quick actions
  const { period } = useDashboardPeriod();
  const store = getStoreCurrency();
  const [hoverIndex, setHoverIndex] = useState<number | undefined>(undefined);
  const [chartMetric, setChartMetric] = useState<'both' | 'revenue' | 'orders'>('both');
  const chartRef = useRef<any>(null);

  // Fetch real data or use dummy data based on toggle
  const { data, isLoading, error, refetch } = useOverviewAnalytics(DUMMY_DATA);
  
  // Sort order status by importance (completed first)
  const sortedOrderStatus = useMemo(() => {
    const statusOrder = ['completed', 'processing', 'pending', 'on-hold', 'cancelled', 'refunded', 'failed'];
    const orderStatus = data.orderStatus || data.orderStatusDistribution || [];
    if (!Array.isArray(orderStatus)) return [];
    
    return [...orderStatus].sort((a, b) => {
      const statusA = (a.status || a.name || '').toLowerCase();
      const statusB = (b.status || b.name || '').toLowerCase();
      const posA = statusOrder.indexOf(statusA);
      const posB = statusOrder.indexOf(statusB);
      return (posA === -1 ? 999 : posA) - (posB === -1 ? 999 : posB);
    });
  }, [data.orderStatus, data.orderStatusDistribution]);
  
  // Auto-select first status (completed) on load
  const [activeStatus, setActiveStatus] = useState(
    sortedOrderStatus[0]?.status || sortedOrderStatus[0]?.name || 'All'
  );

  // Filter chart data based on period
  const chartData = useMemo(() => {
    return period === 'all' ? data.salesChart : data.salesChart.slice(-Number(period));
  }, [period, data]);
  
  // Calculate metrics based on period (for comparison)
  const periodMetrics = useMemo(() => {
    if (period === 'all') {
      // For "all time", no comparison
      const currentRevenue = data.salesChart.reduce((sum: number, d: any) => sum + d.revenue, 0);
      const currentOrders = data.salesChart.reduce((sum: number, d: any) => sum + d.orders, 0);
      
      return {
        revenue: { current: currentRevenue, change: undefined },
        orders: { current: currentOrders, change: undefined },
        avgOrderValue: { current: currentOrders > 0 ? currentRevenue / currentOrders : 0, change: undefined },
        conversionRate: { current: data?.metrics?.conversionRate?.today ?? 0, change: undefined },
      };
    }
    
    const currentData = chartData;
    const previousData = data.salesChart.slice(-Number(period) * 2, -Number(period));
    
    const currentRevenue = currentData.reduce((sum: number, d: any) => sum + d.revenue, 0);
    const previousRevenue = previousData.reduce((sum: number, d: any) => sum + d.revenue, 0);
    const currentOrders = currentData.reduce((sum: number, d: any) => sum + d.orders, 0);
    const previousOrders = previousData.reduce((sum: number, d: any) => sum + d.orders, 0);
    
    // Get conversion rate from real API data
    const currentConversionRate = data?.metrics?.conversionRate?.today ?? 0;
    const previousConversionRate = data?.metrics?.conversionRate?.yesterday ?? 0;
    
    return {
      revenue: {
        current: currentRevenue,
        change: previousRevenue > 0 ? ((currentRevenue - previousRevenue) / previousRevenue) * 100 : 0,
      },
      orders: {
        current: currentOrders,
        change: previousOrders > 0 ? ((currentOrders - previousOrders) / previousOrders) * 100 : 0,
      },
      avgOrderValue: {
        current: currentOrders > 0 ? currentRevenue / currentOrders : 0,
        change: previousOrders > 0 ? (((currentRevenue / currentOrders) - (previousRevenue / previousOrders)) / (previousRevenue / previousOrders)) * 100 : 0,
      },
      conversionRate: {
        current: currentConversionRate,
        change: previousConversionRate > 0 ? ((currentConversionRate - previousConversionRate) / previousConversionRate) * 100 : 0,
      },
    };
  }, [chartData, period]);

  // Show loading state
  if (isLoading) {
    return <LoadingState text={__('Loading analytics...')} className="h-96" />;
  }

  // Show error state
  if (error) {
    return (
      <ErrorCard
        title={__('Failed to load dashboard analytics')}
        message={getPageLoadErrorMessage(error)}
        onRetry={() => refetch()}
      />
    );
  }

  // Event handlers
  const onPieEnter = (_: any, index: number) => {
    setHoverIndex(index);
  };

  const onPieLeave = () => {
    setHoverIndex(undefined);
  };

  const handleChartMouseLeave = () => {
    setHoverIndex(undefined);
  };

  const handleChartMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    (document.activeElement as HTMLElement)?.blur();
  };

  return (
    <div className="space-y-6 lg:p-6 pb-6">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold">{__('Dashboard')}</h1>
        <p className="text-sm text-muted-foreground">{__('Overview of your store performance')}</p>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <MetricCard
          title={__('Revenue')}
          value={periodMetrics.revenue.current}
          change={periodMetrics.revenue.change}
          icon={DollarSign}
          format="money"
          period={period}
        />
        <MetricCard
          title={__('Orders')}
          value={periodMetrics.orders.current}
          change={periodMetrics.orders.change}
          icon={ShoppingCart}
          period={period}
        />
        <MetricCard
          title={__('Avg Order Value')}
          value={periodMetrics.avgOrderValue.current}
          change={periodMetrics.avgOrderValue.change}
          icon={Package}
          format="money"
          period={period}
        />
        <MetricCard
          title={__('Conversion Rate')}
          value={periodMetrics.conversionRate.current}
          change={periodMetrics.conversionRate.change}
          icon={Users}
          format="percent"
          period={period}
        />
      </div>

      {/* Low Stock Alert Banner */}
      {(data?.lowStock?.length ?? 0) > 0 && (
        <div className="-mx-6 px-4 md:px-6 py-3 bg-amber-50 dark:bg-amber-950/20 border-y border-amber-200 dark:border-amber-900/50">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div className="flex items-start sm:items-center gap-3">
              <AlertTriangle className="w-5 h-5 text-amber-600 dark:text-amber-500 flex-shrink-0 mt-0.5 sm:mt-0" />
              <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2 w-full shrink">
                <span className="font-medium text-amber-900 dark:text-amber-100">
                  {data?.lowStock?.length ?? 0} {__('products need attention')}
                </span>
                <span className="text-sm text-amber-700 dark:text-amber-300">
                  {__('Stock levels are running low')}
                </span>
                <Link 
                  to="/products" 
                  className="inline-flex md:hidden items-center gap-1 text-sm font-medium text-amber-900 dark:text-amber-100 hover:text-amber-700 dark:hover:text-amber-300 transition-colors self-end"
                >
                  {__('View products')} <ArrowUpRight className="w-4 h-4" />
                </Link>
              </div>
            </div>
            <Link 
              to="/products" 
              className="hidden md:inline-flex items-center gap-1 text-sm font-medium text-amber-900 dark:text-amber-100 hover:text-amber-700 dark:hover:text-amber-300 transition-colors"
            >
              {__('View products')} <ArrowUpRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      )}

      {/* Main Chart */}
      <div className="rounded-lg border bg-card p-6">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-lg font-semibold">{__('Sales Overview')}</h2>
            <p className="text-sm text-muted-foreground">{__('Revenue and orders over time')}</p>
          </div>
          <Select value={chartMetric} onValueChange={(value) => setChartMetric(value as 'both' | 'revenue' | 'orders')}>
            <SelectTrigger className="w-[140px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="revenue">{__('Revenue')}</SelectItem>
              <SelectItem value="orders">{__('Orders')}</SelectItem>
              <SelectItem value="both">{__('Both')}</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <ResponsiveContainer width="100%" height={300}>
          {chartMetric === 'both' ? (
            <ComposedChart data={chartData}>
              <defs>
                <linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.4} />
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0.05} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="date" className="text-xs" />
              <YAxis yAxisId="left" className="text-xs" tickFormatter={(value) => {
                const millions = value / 1000000;
                return millions >= 1 ? `${millions.toFixed(0)}${__('M')}` : `${(value / 1000).toFixed(0)}${__('K')}`;
              }} />
              <YAxis yAxisId="right" orientation="right" className="text-xs" />
              <Tooltip
                contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))' }}
                content={({ active, payload, label }) => {
                  if (active && payload && payload.length) {
                    return (
                      <div className="bg-card border border-border rounded p-2">
                        <p className="text-sm font-bold">{label}</p>
                        {payload.map((entry: any, index: number) => (
                          <p key={index} style={{ color: entry.color }}>
                            <span className="font-bold">{entry.name}:</span> {entry.name === __('Revenue') ? formatMoney(Number(entry.value || 0)) : (entry.value ?? 0).toLocaleString()}
                          </p>
                        ))}
                      </div>
                    );
                  }
                  return null;
                }}
              />
              <Legend wrapperStyle={{ paddingTop: '20px' }} />
              <Area yAxisId="left" type="monotone" dataKey="revenue" stroke="#3b82f6" strokeWidth={2.5} fillOpacity={1} fill="url(#colorRevenue)" name={__('Revenue')} />
              <Line yAxisId="right" type="monotone" dataKey="orders" stroke="#10b981" strokeWidth={2.5} dot={{ r: 4, fill: '#10b981' }} activeDot={{ r: 6 }} name={__('Orders')} />
            </ComposedChart>
          ) : chartMetric === 'revenue' ? (
            <AreaChart data={chartData}>
              <defs>
                <linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="date" className="text-xs" />
              <YAxis className="text-xs" tickFormatter={(value) => {
                const millions = value / 1000000;
                return millions >= 1 ? `${millions.toFixed(0)}M` : `${(value / 1000).toFixed(0)}K`;
              }} />
              <Tooltip
                contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))' }}
                content={({ active, payload, label }) => {
                  if (active && payload && payload.length) {
                    return (
                      <div className="bg-card border border-border rounded p-2">
                        <p className="text-sm font-bold">{label}</p>
                        {payload.map((entry: any, index: number) => (
                          <p key={index} style={{ color: entry.color }}>
                            <span className="font-bold">{entry.name}:</span> {formatMoney(Number(entry.value))}
                          </p>
                        ))}
                      </div>
                    );
                  }
                  return null;
                }}
              />
              <Area type="monotone" dataKey="revenue" stroke="#3b82f6" fillOpacity={1} fill="url(#colorRevenue)" name={__('Revenue')} />
            </AreaChart>
          ) : (
            <BarChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis dataKey="date" className="text-xs" />
              <YAxis className="text-xs" />
              <Tooltip
                contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))' }}
                content={({ active, payload, label }) => {
                  if (active && payload && payload.length) {
                    return (
                      <div className="bg-card border border-border rounded p-2">
                        <p className="text-sm font-bold">{label}</p>
                        {payload.map((entry: any, index: number) => (
                          <p key={index} style={{ color: entry.color }}>
                            <span className="font-bold">{entry.name}:</span> {(entry.value ?? 0).toLocaleString()}
                          </p>
                        ))}
                      </div>
                    );
                  }
                  return null;
                }}
              />
              <Bar dataKey="orders" fill="#10b981" radius={[4, 4, 0, 0]} name={__('Orders')} />
            </BarChart>
          )}
        </ResponsiveContainer>
      </div>

      {/* Quick Stats Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Order Status Distribution - Interactive Pie Chart with Dropdown */}
        <div 
          className="rounded-lg border bg-card p-6"
          onMouseDown={handleChartMouseDown}
        >
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold">Order Status Distribution</h3>
            <Select value={activeStatus} onValueChange={setActiveStatus}>
              <SelectTrigger className="w-[160px] h-8">
                <SelectValue />
              </SelectTrigger>
              <SelectContent align="end">
                {sortedOrderStatus.map((status, idx) => {
                  const statusValue = status.status || status.name || `status-${idx}`;
                  return (
                    <SelectItem key={statusValue} value={statusValue}>
                      <span className="flex items-center gap-2 text-xs">
                        <span className="flex h-3 w-3 shrink-0 rounded" style={{ backgroundColor: status.color }} />
                        {statusValue}
                      </span>
                    </SelectItem>
                  );
                })}
              </SelectContent>
            </Select>
          </div>

          <ResponsiveContainer width="100%" height={280}>
            <PieChart 
              ref={chartRef}
              onMouseLeave={handleChartMouseLeave}
            >
              <Pie
                data={sortedOrderStatus}
                dataKey="count"
                nameKey="status"
                cx="50%"
                cy="50%"
                innerRadius={70}
                outerRadius={110}
                strokeWidth={5}
                onMouseEnter={onPieEnter}
                onMouseLeave={onPieLeave}
                isAnimationActive={false}
              >
                {sortedOrderStatus.map((entry: any, index: number) => {
                  const activePieIndex = sortedOrderStatus.findIndex((item: any) => 
                    (item.status || item.name) === activeStatus
                  );
                  const isActive = index === (hoverIndex !== undefined ? hoverIndex : activePieIndex);
                  return (
                    <Cell 
                      key={`cell-${index}`} 
                      fill={entry.color}
                      stroke={isActive ? entry.color : undefined}
                      strokeWidth={isActive ? 8 : 5}
                      opacity={isActive ? 1 : 0.7}
                    />
                  );
                })}
                
                <Label
                  content={({ viewBox }) => {
                    if (viewBox && 'cx' in viewBox && 'cy' in viewBox) {
                      const activePieIndex = sortedOrderStatus.findIndex((item: any) => (item.status || item.name) === activeStatus);
                      const displayIndex = hoverIndex !== undefined ? hoverIndex : (activePieIndex >= 0 ? activePieIndex : 0);
                      const selectedData = sortedOrderStatus[displayIndex];
                      return (
                        <text
                          x={viewBox.cx}
                          y={viewBox.cy}
                          textAnchor="middle"
                          dominantBaseline="middle"
                        >
                          <tspan
                            x={viewBox.cx}
                            y={viewBox.cy}
                            className="fill-foreground text-3xl font-bold"
                          >
                            {(selectedData?.count ?? 0).toLocaleString()}
                          </tspan>
                          <tspan
                            x={viewBox.cx}
                            y={(viewBox.cy || 0) + 24}
                            className="fill-muted-foreground text-sm"
                          >
                            {selectedData?.status || selectedData?.name}
                          </tspan>
                        </text>
                      );
                    }
                  }}
                />
              </Pie>
            </PieChart>
          </ResponsiveContainer>
        </div>

        {/* Top Products & Customers - Tabbed */}
        <div className="rounded-lg border bg-card p-6">
          <Tabs defaultValue="products" className="w-full">
            <div className="flex items-center justify-between mb-4">
              <TabsList>
                <TabsTrigger value="products">{__('Top Products')}</TabsTrigger>
                <TabsTrigger value="customers">{__('Top Customers')}</TabsTrigger>
              </TabsList>
              <Link to="/products" className="text-sm text-primary hover:underline flex items-center gap-1">
                {__('View all')} <ArrowUpRight className="w-3 h-3" />
              </Link>
            </div>
            
            <TabsContent value="products" className="mt-0">
              <div className="space-y-3">
                {(data.topProducts || DUMMY_DATA.topProducts).slice(0, 5).map((product: any, index: number) => (
                  <div key={product.product_id || product.id || index} className="flex items-center justify-between p-2 rounded hover:bg-muted/50">
                    <div className="flex items-center gap-3 flex-1">
                      <div className="text-2xl">{product.image || '📦'}</div>
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-sm truncate">{product.name}</div>
                        <div className="text-xs text-muted-foreground">{product.items_sold || product.sales} {__('sold')}</div>
                      </div>
                    </div>
                    <div className="text-sm font-medium">{formatMoney(product.revenue)}</div>
                  </div>
                ))}
              </div>
            </TabsContent>
            
            <TabsContent value="customers" className="mt-0">
              <div className="space-y-3">
                {(data.topCustomers || DUMMY_DATA.topCustomers).slice(0, 5).map((customer: any, index: number) => (
                  <div key={customer.customer_id || customer.id || index} className="flex items-center justify-between p-2 rounded hover:bg-muted/50">
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-sm truncate">{customer.name}</div>
                      <div className="text-xs text-muted-foreground">{customer.order_count || customer.orders} {__('orders')}</div>
                    </div>
                    <div className="text-sm font-medium">{formatMoney(customer.total_spent || customer.total)}</div>
                  </div>
                ))}
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </div>

    </div>
  );
}
