function StatCard({ title, value, trend, icon, color }) {
  const isPositive = trend > 0;
  
  return (
    <div className="card hover:shadow-md transition-shadow">
      <div className="flex items-start justify-between mb-4">
        <div className={`w-12 h-12 rounded-lg flex items-center justify-center ${color} bg-opacity-10`}>
          <span className={`${icon} text-2xl ${color.replace('bg-', 'text-')}`}></span>
        </div>
        {trend !== undefined && (
            <span className={`text-sm font-medium ${isPositive ? 'text-green-600' : 'text-red-600'} flex items-center`}>
            {isPositive ? <span className="icon-arrow-up mr-1 w-4 h-4"></span> : <span className="icon-arrow-down mr-1 w-4 h-4"></span>}
            {Math.abs(trend)}%
            </span>
        )}
      </div>
      <h3 className="text-gray-500 text-sm font-medium mb-1">{title}</h3>
      <p className="text-2xl font-bold text-gray-900">{value}</p>
    </div>
  );
}

function Dashboard({ onChangeView }) {
  const { stats, transactions, products, users, formatLKR, getProductTotalStock } = window.MockData;
  const chartRef = React.useRef(null);
  const chartInstance = React.useRef(null);

  const [chartPeriod, setChartPeriod] = React.useState('7days');

  React.useEffect(() => {
    if (chartRef.current) {
        if (chartInstance.current) {
            chartInstance.current.destroy();
        }
        
        const ctx = chartRef.current.getContext('2d');
        const ChartJS = window.ChartJS;

        let chartLabels, chartData;
        if (chartPeriod === '7days') {
            chartLabels = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Day 7'];
            chartData = [0, 0, 0, 0, 0, 0, 0];
        } else if (chartPeriod === 'month') {
            chartLabels = ['Week 1', 'Week 2', 'Week 3', 'Week 4'];
            chartData = [0, 0, 0, 0];
        } else if (chartPeriod === 'year') {
            chartLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            chartData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        }

        chartInstance.current = new ChartJS(ctx, {
            type: 'line',
            data: {
            labels: chartLabels,
            datasets: [{
                label: 'Revenue (LKR)',
                data: chartData,
                borderColor: '#059669',
                backgroundColor: 'rgba(5, 150, 105, 0.1)',
                fill: true,
                tension: 0.4,
                pointRadius: 4,
                pointBackgroundColor: '#fff',
                pointBorderColor: '#059669',
                pointBorderWidth: 2
            }]
            },
            options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: '#1e293b',
                    padding: 12,
                    cornerRadius: 8,
                    displayColors: false,
                    callbacks: {
                        label: function(context) {
                            return 'LKR ' + context.parsed.y.toLocaleString();
                        }
                    }
                }
            },
            scales: {
                y: {
                beginAtZero: true,
                grid: {
                    color: '#f1f5f9',
                    drawBorder: false
                },
                ticks: { color: '#94a3b8' }
                },
                x: {
                grid: { display: false },
                ticks: { color: '#94a3b8' }
                }
            }
            }
        });
    }

    return () => {
        if (chartInstance.current) {
            chartInstance.current.destroy();
        }
    };
  }, [chartPeriod]);

  // Low stock products logic
  const lowStockProducts = products.filter(p => 
    p.variations.some(v => v.stock < v.lowStockThreshold)
  );

  // Cashier Performance Logic
  const cashierStats = users.filter(u => u.role === 'cashier').map(user => {
      const userTrx = transactions.filter(t => t.cashierId === user.id);
      const totalSales = userTrx.reduce((sum, t) => sum + t.total, 0);
      const count = userTrx.length;
      return { ...user, totalSales, count };
  });

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex items-center justify-between">
        <div>
            <h1 className="text-2xl font-bold text-gray-900">Store Overview</h1>
            <p className="text-gray-500 text-sm">Welcome back, Manager</p>
        </div>
        <div className="flex gap-2">
            <button 
                onClick={() => onChangeView && onChangeView('reports')} 
                className="btn btn-secondary text-sm"
            >
                <span className="icon-download mr-2"></span> Report
            </button>
            <button 
                onClick={() => onChangeView && onChangeView('pos')}
                className="btn btn-primary text-sm"
            >
                <span className="icon-plus mr-2"></span> New Sale
            </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard 
          title="Total Sales Today" 
          value={formatLKR(stats.salesToday)} 
          trend={12.5} 
          icon="icon-dollar-sign" 
          color="bg-emerald-600" 
        />
        <StatCard 
          title="Orders Today" 
          value={stats.ordersToday} 
          trend={-2.4} 
          icon="icon-shopping-bag" 
          color="bg-blue-500" 
        />
        {/* New Credit Stats */}
        <StatCard 
          title="Outstanding Credits" 
          value={formatLKR(stats.outstandingCreditValue)} 
          icon="icon-receipt" 
          color="bg-orange-500" 
        />
        <StatCard 
          title="Inventory Value" 
          value={formatLKR(stats.totalInventoryValue)} 
          trend={5.8} 
          icon="icon-package" 
          color="bg-purple-500" 
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Sales Chart */}
        <div className="lg:col-span-2 card">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold text-gray-800">Revenue Analytics</h3>
            <select 
              className="bg-gray-50 border border-gray-200 text-sm rounded-lg px-3 py-1 outline-none"
              value={chartPeriod}
              onChange={(e) => setChartPeriod(e.target.value)}
            >
              <option value="7days">Last 7 Days</option>
              <option value="month">This Month</option>
              <option value="year">This Year</option>
            </select>
          </div>
          <div className="h-72">
            <canvas ref={chartRef}></canvas>
          </div>
        </div>

        {/* Low Stock Alert */}
        <div className="card">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-bold text-gray-800">Low Stock Alerts</h3>
            <span className="badge bg-red-100 text-red-700">{lowStockProducts.length} Items</span>
          </div>
          <div className="space-y-4">
            {lowStockProducts.slice(0, 4).map(product => {
                const totalStock = getProductTotalStock(product);
                return (
                <div key={product.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-100">
                    <div className="w-12 h-12 rounded bg-gray-100 flex items-center justify-center flex-shrink-0">
                        <span className="icon-image text-gray-400"></span>
                    </div>
                    <div className="flex-1 min-w-0">
                    <h4 className="font-medium text-gray-900 truncate">{product.name}</h4>
                    <p className="text-xs text-gray-500">{product.variations.filter(v => v.stock < v.lowStockThreshold).length} variants low</p>
                    </div>
                    <div className="text-right">
                    <span className="block text-sm font-bold text-red-600">
                        {totalStock} left
                    </span>
                    </div>
                </div>
            )})}
            <button onClick={() => onChangeView && onChangeView('inventory')} className="w-full text-center text-sm text-[var(--primary)] font-medium hover:underline mt-2">
              View All Low Stock
            </button>
          </div>
        </div>
      </div>

      {/* Cashier Performance Section */}
      <div className="card">
        <h3 className="text-lg font-bold text-gray-800 mb-6">Cashier Performance (Today)</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {cashierStats.map(cashier => (
                <div key={cashier.id} className="bg-gray-50 rounded-xl p-4 border border-gray-200 flex items-center gap-4">
                    <div className="w-14 h-14 rounded-full bg-slate-200 flex items-center justify-center text-slate-500 font-bold text-lg shadow-sm border-2 border-white">
                        {cashier.name.split(' ').map(n => n[0]).join('').substring(0, 2)}
                    </div>
                    <div className="flex-1">
                        <h4 className="font-bold text-gray-900">{cashier.name}</h4>
                        <div className="flex gap-4 mt-1">
                            <div>
                                <p className="text-xs text-gray-500">Sales</p>
                                <p className="font-bold text-[var(--primary)]">{formatLKR(cashier.totalSales)}</p>
                            </div>
                            <div>
                                <p className="text-xs text-gray-500">Orders</p>
                                <p className="font-bold text-gray-700">{cashier.count}</p>
                            </div>
                        </div>
                    </div>
                </div>
            ))}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Transactions */}
        <div className="card">
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-bold text-gray-800">Recent Transactions</h3>
                <button onClick={() => onChangeView && onChangeView('reports')} className="text-sm text-[var(--primary)] font-medium">View All</button>
            </div>
            <div className="overflow-x-auto">
                <table className="w-full text-sm text-left">
                    <thead className="text-xs text-gray-500 uppercase bg-gray-50">
                        <tr>
                            <th className="px-4 py-3 rounded-l-lg">Invoice</th>
                            <th className="px-4 py-3">Cashier</th>
                            <th className="px-4 py-3">Amount</th>
                            <th className="px-4 py-3">Status</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {transactions.map(trx => {
                            const cashier = users.find(u => u.id === trx.cashierId) || { name: 'Unknown' };
                            return (
                                <tr key={trx.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 font-medium text-gray-900">{trx.id}</td>
                                    <td className="px-4 py-3 flex items-center gap-2">
                                        <div className="w-6 h-6 rounded-full bg-slate-200 flex items-center justify-center text-xs text-slate-500 font-bold">
                                            {cashier.name.split(' ').map(n => n[0]).join('').substring(0, 1)}
                                        </div>
                                        <span className="truncate max-w-[100px]">{cashier.name}</span>
                                    </td>
                                    <td className="px-4 py-3 font-semibold">{formatLKR(trx.total)}</td>
                                    <td className="px-4 py-3">
                                        <span className={`badge ${trx.status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                                            {trx.status}
                                        </span>
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>
        </div>

        {/* Top Products */}
        <div className="card">
            <h3 className="text-lg font-bold text-gray-800 mb-6">Top Performing Products</h3>
            <div className="space-y-4">
                {products.slice(0, 3).map((product, idx) => (
                    <div key={product.id} className="flex items-center gap-4">
                        <span className="text-2xl font-bold text-gray-300 w-6">#{idx + 1}</span>
                        <div className="w-16 h-16 rounded-lg overflow-hidden bg-gray-100 flex-shrink-0">
                            <img src={product.image} alt={product.name} className="w-full h-full object-cover" />
                        </div>
                        <div className="flex-1">
                            <h4 className="font-bold text-gray-900">{product.name}</h4>
                            <p className="text-sm text-gray-500">{product.category} • {product.brand}</p>
                        </div>
                        <div className="text-right">
                            <p className="font-bold text-gray-900">{formatLKR(product.price)}</p>
                            <p className="text-xs text-green-600 font-medium">+12% sales</p>
                        </div>
                    </div>
                ))}
            </div>
        </div>
      </div>
    </div>
  );
}