import React, { useEffect, useState } from "react";
import { getProducts } from "../api/productApi";
import { getWarehouses } from "../api/warehouseApi";
import { getTransactions } from "../api/transactionApi";
import Layout from "../components/Layout";

const DashboardPage = ({ user, setUser }) => {
  const [summary, setSummary] = useState({
    products: 0,
    warehouses: 0,
    transactions: 0,
    availableUnits: 0
  });

  useEffect(() => {
    const loadSummary = async () => {
      const [products, warehouses, transactions] = await Promise.all([
        getProducts(),
        getWarehouses(),
        getTransactions()
      ]);

      const availableUnits = products.reduce((total, product) => total + Number(product.quantityInStock || 0), 0);
      setSummary({
        products: products.length,
        warehouses: warehouses.length,
        transactions: transactions.length,
        availableUnits
      });
    };

    loadSummary();
  }, []);

  const cards = [
    { label: "Products", value: summary.products },
    { label: "Warehouses", value: summary.warehouses },
    { label: "Transactions", value: summary.transactions },
    { label: "Available Units", value: summary.availableUnits }
  ];

  return (
    <Layout title="Dashboard" user={user} setUser={setUser}>
      <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {cards.map((card) => (
          <div key={card.label} className="rounded-md border border-primary p-5">
            <p className="text-sm font-semibold">{card.label}</p>
            <p className="mt-3 text-3xl font-bold">{card.value}</p>
          </div>
        ))}
      </section>

      <section className="mt-6 rounded-md border border-primary p-5">
        <h3 className="mb-2 text-lg font-bold">StockHub Ltd</h3>
        <p className="text-sm leading-6">
          This system records product details, warehouse information and stock movement transactions for daily,
          weekly and monthly stock reports.
        </p>
      </section>
    </Layout>
  );
};

export default DashboardPage;
