 import { useState, useEffect } from "react";
import axios from '../axiosInstance';

function Reports() {

    const [products, setProducts] = useState([]);
    const [warehouses, setWarehouses] = useState([]);
    const [stockTransaction, setStockTransaction] = useState([]);
    const [error, setError] = useState('');

    const fetchAllReports = async () => {
        try {
            const prodRes = await axios.get('http://localhost:5000/api/product');
            setProducts(prodRes.data);

            const whRes = await axios.get('http://localhost:5000/api/warehouse');
            setWarehouses(whRes.data);

            const txRes = await axios.get('http://localhost:5000/api/stockTransaction');
            setStockTransaction(txRes.data);
        } catch (error) {
            setError("Failed to generate report summaries.");
        }
    };

    useEffect(() => {
        fetchAllReports();
    }, []);

    const today = new Date();

    const dailyTransactions = stockTransaction.filter((tx) => {
        if (!tx.transactionDate) return false;
        const txDate = new Date(tx.transactionDate);
        return txDate.toDateString() === today.toDateString();
    });

    const weeklyTransactions = stockTransaction.filter((tx) => {
        if (!tx.transactionDate) return false;

        const txDate = new Date(tx.transactionDate);

        const startOfWeek = new Date(today);
        startOfWeek.setHours(0, 0, 0, 0);
        startOfWeek.setDate(today.getDate() - today.getDay());

        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6);
        endOfWeek.setHours(23, 59, 59, 999);

        return txDate >= startOfWeek && txDate <= endOfWeek;
    });

    const monthlyTransactions = stockTransaction.filter((tx) => {
        if (!tx.transactionDate) return false;

        const txDate = new Date(tx.transactionDate);

        return (
            txDate.getMonth() === today.getMonth() &&
            txDate.getFullYear() === today.getFullYear()
        );
    });

    const dailyQuantity = dailyTransactions.reduce(
        (sum, tx) => sum + Number(tx.quantityMoved || 0),
        0
    );

    const weeklyQuantity = weeklyTransactions.reduce(
        (sum, tx) => sum + Number(tx.quantityMoved || 0),
        0
    );

    const monthlyQuantity = monthlyTransactions.reduce(
        (sum, tx) => sum + Number(tx.quantityMoved || 0),
        0
    );

    return (
        <div className="p-6 bg-slate-50 min-h-screen flex flex-col gap-8">

            <div>
                <h2 className="text-2xl font-bold text-slate-800">System Summary Reports</h2>
                <p className="text-sm text-slate-500">Live summary data across your inventory portal.</p>
            </div>

            {error && (
                <p className="text-red-500 bg-red-100 p-2 rounded text-sm font-semibold text-center">
                    {error}
                </p>
            )}

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <span className="text-xs font-bold text-slate-400 uppercase">
                        Total Items
                    </span>
                    <h4 className="text-2xl font-extrabold text-blue-600">
                        {products.length} Products
                    </h4>
                </div>

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <span className="text-xs font-bold text-slate-400 uppercase">
                        Active Spots
                    </span>
                    <h4 className="text-2xl font-extrabold text-green-600">
                        {warehouses.length} Warehouses
                    </h4>
                </div>

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <span className="text-xs font-bold text-slate-400 uppercase">
                        Logged Activity
                    </span>
                    <h4 className="text-2xl font-extrabold text-purple-600">
                        {stockTransaction.length} Logs
                    </h4>
                </div>

            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <span className="text-xs font-bold text-slate-400 uppercase">
                        Daily Report
                    </span>
                    <h4 className="text-2xl font-extrabold text-blue-600">
                        {dailyTransactions.length} Transactions
                    </h4>
                    <p className="text-sm text-slate-500">
                        {dailyQuantity} Units Moved Today
                    </p>
                </div>

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <span className="text-xs font-bold text-slate-400 uppercase">
                        Weekly Report
                    </span>
                    <h4 className="text-2xl font-extrabold text-green-600">
                        {weeklyTransactions.length} Transactions
                    </h4>
                    <p className="text-sm text-slate-500">
                        {weeklyQuantity} Units Moved This Week
                    </p>
                </div>

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <span className="text-xs font-bold text-slate-400 uppercase">
                        Monthly Report
                    </span>
                    <h4 className="text-2xl font-extrabold text-purple-600">
                        {monthlyTransactions.length} Transactions
                    </h4>
                    <p className="text-sm text-slate-500">
                        {monthlyQuantity} Units Moved This Month
                    </p>
                </div>

            </div>

            <div className="bg-white rounded shadow-sm border border-slate-200 flex flex-col gap-2 p-4">

                <h3 className="text-lg font-bold text-slate-700">
                    Available Products Summary
                </h3>

                <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">

                        <thead>
                            <tr className="bg-slate-100 border-b border-slate-200 text-slate-700 text-sm font-bold">
                                <th className="p-3">Product Code</th>
                                <th className="p-3">Product Name</th>
                                <th className="p-3">Category</th>
                                <th className="p-3">Quantity In Stock</th>
                                <th className="p-3">Unit Price</th>
                                <th className="p-3">Supplier Name</th>
                                <th className="p-3">Date</th>
                            </tr>
                        </thead>

                        <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                            {Array.isArray(products) && products.map((prod) => (
                                <tr key={prod._id} className="hover:bg-slate-50">
                                    <td className="p-3 font-semibold text-slate-700">
                                        {prod.productCode}
                                    </td>
                                    <td className="p-3">{prod.productName}</td>
                                    <td className="p-3">{prod.category}</td>
                                    <td className="p-3">{prod.quantityInStock}</td>
                                    <td className="p-3">${prod.unitPrice}</td>
                                    <td className="p-3">{prod.supplierName}</td>
                                    <td className="p-3">
                                        {prod.date
                                            ? prod.date.substring(0, 10)
                                            : (prod.dateReceived
                                                ? prod.dateReceived.substring(0, 10)
                                                : "")}
                                    </td>
                                </tr>
                            ))}
                        </tbody>

                    </table>
                </div>

            </div>

            <div className="bg-white rounded shadow-sm border border-slate-200 flex flex-col gap-2 p-4">

                <h3 className="text-lg font-bold text-slate-700">
                    Warehouse Setup Summary
                </h3>

                <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">

                        <thead>
                            <tr className="bg-slate-100 border-b border-slate-200 text-slate-700 text-sm font-bold">
                                <th className="p-3">Warehouse Code</th>
                                <th className="p-3">Warehouse Name</th>
                                <th className="p-3">Warehouse Location</th>
                            </tr>
                        </thead>

                        <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                            {Array.isArray(warehouses) && warehouses.map((wh) => (
                                <tr key={wh._id} className="hover:bg-slate-50">
                                    <td className="p-3 font-semibold text-slate-700">
                                        {wh.warehouseCode}
                                    </td>
                                    <td className="p-3">{wh.warehouseName}</td>
                                    <td className="p-3">{wh.warehouseLocation}</td>
                                </tr>
                            ))}
                        </tbody>

                    </table>
                </div>

            </div>

            <div className="bg-white rounded shadow-sm border border-slate-200 flex flex-col gap-2 p-4">

                <h3 className="text-lg font-bold text-slate-700">
                    Stock Activity Logs
                </h3>

                <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">

                        <thead>
                            <tr className="bg-slate-100 border-b border-slate-200 text-slate-700 text-sm font-bold">
                                <th className="p-3">Transaction Date</th>
                                <th className="p-3">Quantity Moved</th>
                                <th className="p-3">Transaction Type</th>
                            </tr>
                        </thead>

                        <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                            {Array.isArray(stockTransaction) && stockTransaction.map((tx) => (
                                <tr key={tx._id} className="hover:bg-slate-50">
                                    <td className="p-3">
                                        {tx.transactionDate
                                            ? tx.transactionDate.substring(0, 10)
                                            : ""}
                                    </td>

                                    <td className="p-3 font-semibold">
                                        {tx.quantityMoved}
                                    </td>

                                    <td className="p-3">
                                        <span
                                            className={`px-2 py-0.5 rounded text-xs font-bold ${
                                                tx.transactionType?.toLowerCase().includes('in')
                                                    ? 'bg-green-100 text-green-700'
                                                    : 'bg-amber-100 text-amber-700'
                                            }`}
                                        >
                                            {tx.transactionType}
                                        </span>
                                    </td>

                                </tr>
                            ))}
                        </tbody>

                    </table>
                </div>

            </div>

        </div>
    );
}

export default Reports;