import React, { useEffect, useState } from 'react';
import { getProducts, getSales, getStocks } from '../utils/api';
import { useAuth } from '../utils/AuthContext';

const StatCard = ({ title, value, icon, color, sub }) => (
  <div className={`bg-white rounded-xl border border-slate-200 p-5 flex items-start gap-4`}>
    <div className={`w-12 h-12 rounded-xl flex items-center justify-center text-2xl ${color}`}>
      {icon}
    </div>
    <div>
      <p className="text-sm text-slate-500">{title}</p>
      <p className="text-2xl font-bold text-slate-800 mt-0.5">{value}</p>
      {sub && <p className="text-xs text-slate-400 mt-0.5">{sub}</p>}
    </div>
  </div>
);

export default function Dashboard() {
  const { user } = useAuth();
  const [stats, setStats] = useState({ products: 0, sales: 0, revenue: 0, lowStock: 0 });
  const [recentSales, setRecentSales] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([getProducts(), getSales(), getStocks()])
      .then(([p, s, st]) => {
        const revenue = s.data.reduce((sum, sale) => sum + sale.soldTotalPrice, 0);
        const lowStock = st.data.filter(s => s.remainingQuantity <= 5).length;
        setStats({
          products: p.data.length,
          sales: s.data.length,
          revenue,
          lowStock,
        });
        setRecentSales(s.data.slice(0, 5));
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  if (loading) return (
    <div className="flex items-center justify-center h-48">
      <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
    </div>
  );

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-slate-800">Welcome back, {user?.username} 👋</h1>
        <p className="text-slate-500 text-sm mt-0.5">Here's what's happening at DAB Enterprise today</p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4 mb-8">
        <StatCard title="Total Products" value={stats.products} icon="📦" color="bg-blue-50" />
        <StatCard title="Total Sales" value={stats.sales} icon="🛒" color="bg-green-50" />
        <StatCard title="Total Revenue" value={`RWF ${stats.revenue.toLocaleString()}`} icon="💰" color="bg-yellow-50" />
        <StatCard
          title="Low Stock Items"
          value={stats.lowStock}
          icon="⚠️"
          color="bg-red-50"
          sub={stats.lowStock > 0 ? 'Needs attention' : 'All good'}
        />
      </div>

      {/* Recent sales */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100">
          <h2 className="font-semibold text-slate-800 text-sm">Recent Sales</h2>
        </div>
        {recentSales.length === 0 ? (
          <div className="px-5 py-10 text-center text-slate-400 text-sm">No sales recorded yet</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50">
                <tr>
                  <th className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Product</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Qty</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Unit Price</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Total</th>
                  <th className="text-left px-5 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Date</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {recentSales.map(s => (
                  <tr key={s._id} className="hover:bg-slate-50">
                    <td className="px-5 py-3 font-medium text-slate-800">{s.productId?.productName || 'N/A'}</td>
                    <td className="px-5 py-3 text-slate-600">{s.soldQuantity}</td>
                    <td className="px-5 py-3 text-slate-600">RWF {s.soldUnitPrice?.toLocaleString()}</td>
                    <td className="px-5 py-3 font-semibold text-green-700">RWF {s.soldTotalPrice?.toLocaleString()}</td>
                    <td className="px-5 py-3 text-slate-400">{new Date(s.salesDate).toLocaleDateString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
