import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { 
  Package, 
  AlertTriangle, 
  CheckCircle, 
  ArrowUpRight, 
  Coins, 
  ShoppingCart 
} from 'lucide-react';

function Dashboard() {
  const [metrics, setMetrics] = useState({
    totalProducts: 0,
    totalStockValue: 0,
    totalSoldUnits: 0,
    lowStockAlerts: 0
  });
  const [lowStockItems, setLowStockItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDashboardMatrix = async () => {
      try {
        setLoading(true);
        // Pull context directly from your Left-Join /api/stock router
        const stockRes = await axios.get('http://localhost:5000/api/stock');
        const data = stockRes.data;

        // Calculate dynamic real-time administrative metrics
        let totalProducts = data.length;
        let totalStockValue = 0;
        let totalSoldUnits = 0;
        let lowStockAlerts = 0;
        let criticalList = [];

        data.forEach(item => {
          const remaining = item.remaining_quantity ?? 0;
          const price = item.unit_price ?? 0;
          
          totalStockValue += remaining * price;
          totalSoldUnits += item.sold_quantity ?? 0;

          // Flag items under a low stock threshold of 5 units
          if (remaining <= 5) {
            lowStockAlerts++;
            criticalList.push({
              id: item.product_id,
              name: item.product_name,
              category: item.category,
              remaining: remaining
            });
          }
        });

        setMetrics({
          totalProducts,
          totalStockValue,
          totalSoldUnits,
          lowStockAlerts
        });
        setLowStockItems(criticalList); // Show all dynamic low-stock warnings
      } catch (err) {
        console.error("Dashboard engine compilation breakdown:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardMatrix();
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600"></div>
        <span className="ml-3 text-sm font-medium text-slate-500">Compiling Analytics Matrix...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-7xl mx-auto px-4 py-2">
      
      {/* Upper Welcoming Header Row */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-slate-800 tracking-tight">Enterprise Operations Control</h1>
          <p className="text-sm font-medium text-slate-500">Real-time status overview of master warehouse stock and logistics distribution.</p>
        </div>
        <div className="text-xs font-semibold px-3 py-1.5 bg-slate-100 rounded-xl text-slate-600 self-start md:self-auto">
          System Live Balance Channel
        </div>
      </div>

      {/* Analytics Summary Scorecards Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        
        {/* Total Products Card */}
        <div className="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div className="space-y-1">
            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Catalog Profile</span>
            <h3 className="text-2xl font-black text-slate-800 font-mono">{metrics.totalProducts}</h3>
            <p className="text-xs text-slate-500 flex items-center gap-1">Active items registered</p>
          </div>
          <div className="p-3 bg-indigo-50 text-indigo-600 rounded-xl">
            <Package size={22} />
          </div>
        </div>

        {/* Inventory Value Card - Adjusted to RWF format without fractional decimals */}
        <div className="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div className="space-y-1">
            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Stock Valuation</span>
            <h3 className="text-2xl font-black text-slate-800 font-mono">
              FRW {metrics.totalStockValue.toLocaleString(undefined, { maximumFractionDigits: 0 })}
            </h3>
            <p className="text-xs text-emerald-600 flex items-center gap-0.5 font-medium">
              Asset holding pool
            </p>
          </div>
          <div className="p-3 bg-emerald-50 text-emerald-600 rounded-xl">
            <Coins size={22} />
          </div>
        </div>

        {/* Units Sold Card */}
        <div className="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div className="space-y-1">
            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Sales Vol</span>
            <h3 className="text-2xl font-black text-slate-800 font-mono">{metrics.totalSoldUnits}</h3>
            <p className="text-xs text-slate-500 flex items-center gap-1">Units cleared outwards</p>
          </div>
          <div className="p-3 bg-blue-50 text-blue-600 rounded-xl">
            <ShoppingCart size={22} />
          </div>
        </div>

        {/* Low Stock Threshold Warnings */}
        <div className="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div className="space-y-1">
            <span className="text-xs font-bold text-slate-400 uppercase tracking-wider">Restock Triggers</span>
            <h3 className={`text-2xl font-black font-mono ${metrics.lowStockAlerts > 0 ? 'text-rose-600' : 'text-slate-800'}`}>
              {metrics.lowStockAlerts}
            </h3>
            <p className="text-xs text-slate-500 font-medium">Items with &le; 5 units left</p>
          </div>
          <div className={`p-3 rounded-xl ${metrics.lowStockAlerts > 0 ? 'bg-rose-50 text-rose-600 animate-pulse' : 'bg-slate-50 text-slate-400'}`}>
            <AlertTriangle size={22} />
          </div>
        </div>
      </div>

      {/* Actionable Restock Logistics Alert Panel */}
      <div className="bg-white p-6 rounded-2xl border border-slate-100 shadow-sm space-y-4">
        <div className="flex items-center justify-between border-b border-slate-50 pb-3">
          <div>
            <h3 className="font-bold text-slate-800 text-base tracking-tight">Critical Warning Manifest</h3>
            <p className="text-xs text-slate-400 font-medium">Items flagged below minimum safe stock limits</p>
          </div>
          {lowStockItems.length > 0 && (
            <span className="px-2.5 py-1 text-xs font-bold bg-rose-50 text-rose-600 rounded-lg">
              Action Required
            </span>
          )}
        </div>

        <div className="divide-y divide-slate-100">
          {lowStockItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center space-y-3">
              <div className="p-3 bg-emerald-50 text-emerald-600 rounded-full">
                <CheckCircle size={24} />
              </div>
              <h4 className="text-sm font-bold text-slate-700">All Stock Channels Stable</h4>
              <p className="text-xs text-slate-400 max-w-sm">No active products fall beneath critical warehouse minimum balances.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
              {lowStockItems.map(item => (
                <div key={item.id} className="p-4 bg-slate-50 rounded-xl flex items-center justify-between border border-slate-100">
                  <div>
                    <h4 className="text-sm font-bold text-slate-800">{item.name}</h4>
                    <p className="text-xs font-medium text-slate-400 capitalize">{item.category}</p>
                  </div>
                  <span className={`px-3 py-1 rounded-lg font-mono font-bold text-xs ${item.remaining === 0 ? 'bg-rose-100 text-rose-700' : 'bg-amber-100 text-amber-800'}`}>
                    {item.remaining === 0 ? 'Out of Stock' : `${item.remaining} Units Left`}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {lowStockItems.length > 0 && (
          <div className="pt-2">
            <a 
              href="/stock" 
              className="w-full md:w-auto inline-flex py-2.5 px-5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-xl items-center justify-center gap-1.5 transition-all shadow-sm shadow-indigo-100"
            >
              Open Stock Correction Matrix <ArrowUpRight size={14} />
            </a>
          </div>
        )}
      </div>
    </div>
  );
}

export default Dashboard;