import { useEffect, useState } from 'react';
import { getAllProducts, getAllTransactions } from '../services/apiService';

const Dashboard = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const [products, setProducts] = useState([]);
  const [transactions, setTransactions] = useState([]);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      setError('');
      try {
        const [pRes, tRes] = await Promise.all([getAllProducts(), getAllTransactions()]);
        setProducts(pRes.data);
        setTransactions(tRes.data);
      } catch (err) {
        setError(err.response?.data?.message || 'Failed to load dashboard');
      } finally {
        setLoading(false);
      }
    };

    load();
  }, []);

  const totalAvailableStock = products.reduce((sum, p) => sum + (p.quantityInStock || 0), 0);
  const recentTransactions = transactions.slice(0, 6);
  const recentProducts = products.slice(0, 6);

  return (
    <div className="max-w-7xl mx-auto p-4 sm:p-6">
      <h2 className="text-2xl sm:text-3xl font-bold mb-6 text-gray-800">Dashboard</h2>

      {loading && (
        <div className="bg-white rounded-lg shadow-md p-6 text-center">
          <p className="text-gray-600">Loading dashboard...</p>
        </div>
      )}

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">{error}</div>
      )}

      {!loading && !error && (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div className="bg-blue-100 rounded-lg shadow-md p-5">
              <h4 className="text-gray-700 font-bold mb-1">Total Available Stock</h4>
              <p className="text-3xl font-bold text-blue-600">{totalAvailableStock}</p>
              <p className="text-xs text-gray-600 mt-1">Units across all products</p>
            </div>

            <div className="bg-white rounded-lg shadow-md p-5 border">
              <h4 className="text-gray-700 font-bold mb-1">Products</h4>
              <p className="text-3xl font-bold text-gray-900">{products.length}</p>
              <p className="text-xs text-gray-600 mt-1">Total catalog items</p>
            </div>

            <div className="bg-white rounded-lg shadow-md p-5 border">
              <h4 className="text-gray-700 font-bold mb-1">Transactions</h4>
              <p className="text-3xl font-bold text-gray-900">{transactions.length}</p>
              <p className="text-xs text-gray-600 mt-1">All recorded movements</p>
            </div>

            <div className="bg-white rounded-lg shadow-md p-5 border">
              <h4 className="text-gray-700 font-bold mb-1">Recent Activity</h4>
              <p className="text-3xl font-bold text-gray-900">{recentTransactions.length}</p>
              <p className="text-xs text-gray-600 mt-1">Latest entries</p>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="text-xl font-bold mb-4 text-gray-800">Recent Transactions</h3>
              {recentTransactions.length ? (
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse text-sm">
                    <thead>
                      <tr className="bg-gray-200">
                        <th className="border px-2 py-2 text-left">Date</th>
                        <th className="border px-2 py-2 text-left">Product</th>
                        <th className="border px-2 py-2 text-right">Qty</th>
                      </tr>
                    </thead>
                    <tbody>
                      {recentTransactions.map((t) => (
                        <tr key={t._id} className="hover:bg-gray-100">
                          <td className="border px-2 py-2">{new Date(t.transactionDate).toLocaleDateString()}</td>
                          <td className="border px-2 py-2">{t.productId?.productName}</td>
                          <td className="border px-2 py-2 text-right">{t.quantityMoved}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="text-gray-600">No transactions yet.</p>
              )}
            </div>

            <div className="bg-white rounded-lg shadow-md p-6">
              <h3 className="text-xl font-bold mb-4 text-gray-800">Recent Products</h3>
              {recentProducts.length ? (
                <div className="overflow-x-auto">
                  <table className="w-full border-collapse text-sm">
                    <thead>
                      <tr className="bg-gray-200">
                        <th className="border px-2 py-2 text-left">Code</th>
                        <th className="border px-2 py-2 text-left">Name</th>
                        <th className="border px-2 py-2 text-right">Qty</th>
                      </tr>
                    </thead>
                    <tbody>
                      {recentProducts.map((p) => (
                        <tr key={p._id} className="hover:bg-gray-100">
                          <td className="border px-2 py-2">{p.productCode}</td>
                          <td className="border px-2 py-2">{p.productName}</td>
                          <td className="border px-2 py-2 text-right">{p.quantityInStock}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="text-gray-600">No products yet.</p>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default Dashboard;

