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

function Reports() {
    const [customer, setCustomer] = useState([]);
    const [product, setProduct] = useState([]);
    const [sale, setSale] = useState([]);
    const [error, setError] = useState("");

    const fetchReports = async () => {
        try {
            const cusRes = await axios.get("http://localhost:5000/api/customer");
            setCustomer(cusRes.data);

            const prRes = await axios.get("http://localhost:5000/api/product");
            setProduct(prRes.data);

            const slRes = await axios.get("http://localhost:5000/api/sale");
            setSale(slRes.data);
        } catch (error) {
            setError("failed to get reports");
        }
    };

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

    const today = new Date();

    const dailySales = sale.filter((sl) => {
        if (!sl.salesDate) return false;
        const d = new Date(sl.salesDate);
        return d.toDateString() === today.toDateString();
    });

    const weeklySales = sale.filter((sl) => {
        if (!sl.salesDate) return false;

        const d = new Date(sl.salesDate);

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

        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6);

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

    const monthlySales = sale.filter((sl) => {
        if (!sl.salesDate) return false;

        const d = new Date(sl.salesDate);

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

    const dailyTotal = dailySales.reduce(
        (sum, s) => sum + Number(s.totalAmountPaid || 0),
        0
    );

    const weeklyTotal = weeklySales.reduce(
        (sum, s) => sum + Number(s.totalAmountPaid || 0),
        0
    );

    const monthlyTotal = monthlySales.reduce(
        (sum, s) => sum + Number(s.totalAmountPaid || 0),
        0
    );

    return (
        <div className="p-6 bg-slate-50 min-h-screen flex flex-col gap-6">
            
            <div className="bg-white p-6 rounded shadow-sm border border-slate-200">
                <h2 className="text-xl font-bold text-slate-700">Sales Management Reports</h2>

                {error && (
                    <p className="text-red-500 bg-red-100 p-2 rounded text-sm font-semibold mt-4 text-center">
                        {error}
                    </p>
                )}
            </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">
                    <h3 className="text-sm text-slate-500">Daily Sales</h3>
                    <p className="text-2xl font-bold text-blue-600">
                        {dailySales.length}
                    </p>
                    <p className="text-sm text-slate-600">
                        ${dailyTotal}
                    </p>
                </div>

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <h3 className="text-sm text-slate-500">Weekly Sales</h3>
                    <p className="text-2xl font-bold text-green-600">
                        {weeklySales.length}
                    </p>
                    <p className="text-sm text-slate-600">
                        ${weeklyTotal}
                    </p>
                </div>

                <div className="bg-white p-4 rounded shadow-sm border border-slate-200">
                    <h3 className="text-sm text-slate-500">Monthly Sales</h3>
                    <p className="text-2xl font-bold text-purple-600">
                        {monthlySales.length}
                    </p>
                    <p className="text-sm text-slate-600">
                        ${monthlyTotal}
                    </p>
                </div>

            </div>

            <div className="bg-white rounded shadow-sm border border-slate-200 overflow-x-auto">
                <div className="p-4 bg-slate-100 border-b border-slate-200">
                    <h3 className="text-md font-bold text-slate-700">
                        Total Customers ({customer.length})
                    </h3>
                </div>

                <table className="w-full text-left border-collapse">
                    <thead>
                        <tr className="bg-slate-50 border-b border-slate-200 text-slate-700 text-sm font-bold">
                            <th className="p-3">customerNumber</th>
                            <th className="p-3">firstName</th>
                            <th className="p-3">lastName</th>
                            <th className="p-3">telephone</th>
                            <th className="p-3">addres</th>
                        </tr>
                    </thead>
                    <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                        {Array.isArray(customer) &&
                            customer.map((cus) => (
                                <tr key={cus._id} className="hover:bg-slate-50">
                                    <td className="p-3 font-semibold">
                                        {cus.customerNumber}
                                    </td>
                                    <td className="p-3">{cus.firstName}</td>
                                    <td className="p-3">{cus.lastName}</td>
                                    <td className="p-3">{cus.telephone}</td>
                                    <td className="p-3">{cus.addres}</td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            </div>

            <div className="bg-white rounded shadow-sm border border-slate-200 overflow-x-auto">
                <div className="p-4 bg-slate-100 border-b border-slate-200">
                    <h3 className="text-md font-bold text-slate-700">
                        Total Products ({product.length})
                    </h3>
                </div>

                <table className="w-full text-left border-collapse">
                    <thead>
                        <tr className="bg-slate-50 border-b border-slate-200 text-slate-700 text-sm font-bold">
                            <th className="p-3">Product Code</th>
                            <th className="p-3">productName</th>
                            <th className="p-3">quantitySold</th>
                            <th className="p-3">unitPrice</th>
                        </tr>
                    </thead>

                    <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                        {Array.isArray(product) &&
                            product.map((pr) => (
                                <tr key={pr._id} className="hover:bg-slate-50">
                                    <td className="p-3 font-semibold">
                                        {pr.productCode}
                                    </td>
                                    <td className="p-3">{pr.productName}</td>
                                    <td className="p-3">{pr.quantitySold}</td>
                                    <td className="p-3">${pr.unitPrice}</td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            </div>

            <div className="bg-white rounded shadow-sm border border-slate-200 overflow-x-auto">
                <div className="p-4 bg-slate-100 border-b border-slate-200">
                    <h3 className="text-md font-bold text-slate-700">
                        Total Sale ({sale.length})
                    </h3>
                </div>

                <table className="w-full text-left border-collapse">
                    <thead>
                        <tr className="bg-slate-50 border-b border-slate-200 text-slate-700 text-sm font-bold">
                            <th className="p-3">InvoiceNumber</th>
                            <th className="p-3">Sales Date</th>
                            <th className="p-3">PaymentMethod</th>
                            <th className="p-3">totalAmountPaid</th>
                        </tr>
                    </thead>

                    <tbody className="text-slate-600 text-sm divide-y divide-slate-100">
                        {Array.isArray(sale) &&
                            sale.map((sl) => (
                                <tr key={sl._id} className="hover:bg-slate-50">
                                    <td className="p-3 font-semibold">
                                        {sl.invoiceNumber}
                                    </td>
                                    <td className="p-3">
                                        {sl.salesDate
                                            ? sl.salesDate.substring(0, 10)
                                            : ""}
                                    </td>
                                    <td className="p-3">
                                        {sl.paymentMethod}
                                    </td>
                                    <td className="p-3">
                                        ${sl.totalAmountPaid}
                                    </td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            </div>

        </div>
    );
}

export default Reports;