import React, { useEffect, useState } from "react";
import { getAllProducts, getAllWarehouses, getAllStocks } from "../api/api";

export default function Dashboard() {
  const [products, setProducts] = useState([]);
  const [warehouses, setWarehouses] = useState([]);
  const [transactions, setTransactions] = useState([]);
  useEffect(() => {
    async function fetchData() {
      try {
        const [productRes, warehouseRes, transactionRes] = await Promise.all([
          getAllProducts(),
          getAllWarehouses(),
          getAllStocks(),
        ]);
        setProducts(productRes.data);
        setWarehouses(warehouseRes.data);
        setTransactions(transactionRes.data);
      } catch (error) {
        console.error(error.response?.data || error.message);
      }
    }
    fetchData();
  }, []);

  const stockIn = transactions.filter((t) => t.TransactionType === 'IN').length;
  const stockOut = transactions.filter((t) => t.TransactionType === 'OUT').length;

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-4 hover:text-olive-600 cursor-pointer">Dashboard</h1>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-sm text-gray-500">Total Products</p>
          <p className="text-2xl font-bold text-gray-800">{products.length}</p>
        </div>
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-sm text-gray-500">Warehouses</p>
          <p className="text-2xl font-bold text-gray-800">{warehouses.length}</p>
        </div>
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-sm text-gray-500">Stock In</p>
          <p className="text-2xl font-bold text-gray-800">{stockIn}</p>
        </div>
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <p className="text-sm text-gray-500">Stock Out</p>
          <p className="text-2xl font-bold text-gray-800">{stockOut}</p>
        </div>
      </div>
    </div>
  );
}
