import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";

export default function Dashboard() {
  const [stats, setStats] = useState({ 
    totalProducts: 0, 
    totalSuppliers: 0, 
    totalStockVolume: 0, 
    totalRevenue: 0 
  });

  useEffect(() => {
    const fetchDashboardStats = async () => {
      try {
        const res = await axios.get("http://localhost:5000/api/data/all");
        
        // Destructure using your true database table names
        const { Products = [], Suppliers = [], SalesOrder = [] } = res.data || {};
        
        // 1. Calculate cumulative operational metrics safely
        const stockVolume = Products.reduce((sum, item) => sum + Number(item.CurrentStock || 0), 0);
        
        // 2. Sum up total financial values recorded from incoming customer shipments
        const revenueSum = SalesOrder.reduce((sum, order) => sum + Number(order.TotalCostAmount || 0), 0);
        
        setStats({
          totalProducts: Products.length,
          totalSuppliers: Suppliers.length,
          totalStockVolume: stockVolume,
          totalRevenue: revenueSum
        });
      } catch (err) {
        console.error("Dashboard metrics loading error:", err);
      }
    };
    fetchDashboardStats();
  }, []);

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6 lg:p-8 flex flex-col gap-6 bg-slate-50/50 min-h-screen">
      
      {/* Top Banner Heading */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-6">
        <span className="text-[10px] font-bold uppercase tracking-wider text-indigo-600 bg-indigo-50 px-2.5 py-1 rounded-full">
          Core System Pipeline Overview
        </span>
        <h2 className="text-3xl font-black text-slate-900 tracking-tight mt-2">
          Stock Management Dashboard
        </h2>
        <p className="text-slate-500 text-sm mt-1">
          Real-time dynamic inventory pipeline tracking metrics and sales evaluations.
        </p>
      </div>

      {/* Dynamic Grid Matrix Display Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        
        {/* Card 1: Total Catalog Items */}
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 border-l-4 border-blue-600 flex flex-col justify-between">
          <div>
            <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Cataloged Items</div>
            <div className="text-3xl font-black text-slate-900 mt-2 font-mono">
              {stats.totalProducts}
            </div>
          </div>
          <p className="text-[11px] text-slate-400 mt-4 font-medium">Distinct inventory products listed.</p>
        </div>

        {/* Card 2: Registered Supply Operations */}
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 border-l-4 border-indigo-500 flex flex-col justify-between">
          <div>
            <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Active Suppliers</div>
            <div className="text-3xl font-black text-slate-900 mt-2 font-mono">
              {stats.totalSuppliers}
            </div>
          </div>
          <p className="text-[11px] text-slate-400 mt-4 font-medium">Verified supplier corporate channels.</p>
        </div>

        {/* Card 3: Total Cumulative Physical Volume */}
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 border-l-4 border-amber-500 flex flex-col justify-between">
          <div>
            <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Warehouse Volume</div>
            <div className="text-3xl font-black text-slate-900 mt-2 font-mono">
              {stats.totalStockVolume.toLocaleString()}
            </div>
          </div>
          <p className="text-[11px] text-slate-400 mt-4 font-medium">Total units currently inside stockroom.</p>
        </div>

        {/* Card 4: Accumulated Gross Sales Earnings */}
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 border-l-4 border-emerald-600 flex flex-col justify-between">
          <div>
            <div className="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Revenue Generated</div>
            <div className="text-2xl font-black text-emerald-600 mt-2.5 font-mono">
              {stats.totalRevenue.toLocaleString()} Rwf
            </div>
          </div>
          <p className="text-[11px] text-slate-400 mt-4 font-medium">Settled cash flow sales transactions total.</p>
        </div>

      </div>

      {/* Navigation Shortcut Row Control */}
      <div className="bg-white rounded-2xl border border-slate-100 shadow-sm p-6 flex flex-wrap items-center gap-4">
        <span className="text-xs font-bold text-slate-500 uppercase tracking-wider mr-2">Quick Management Pipelines:</span>
        <Link to="/Products" className="text-xs bg-slate-900 text-white hover:bg-indigo-600 font-bold px-4 py-2 rounded-xl transition-all shadow-sm">
          + View Inventory Items
        </Link>
        <Link to="/StockInbound" className="text-xs bg-slate-100 text-slate-700 hover:bg-slate-200 font-bold px-4 py-2 rounded-xl transition-all">
          + Log Stock Shipments
        </Link>
        <Link to="/SalesOrder" className="text-xs bg-slate-100 text-slate-700 hover:bg-slate-200 font-bold px-4 py-2 rounded-xl transition-all">
          + Create Sales Orders
        </Link>
      </div>

    </div>
  );
}