import React, { useState, useEffect } from 'react';
import axios from 'axios';

const API_BASE = "http://localhost:5000/api";

const Report = () => {
    const [masterData, setMasterData] = useState([]);
    const [displayData, setDisplayData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [filters, setFilters] = useState({ search: '' });

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

    const fetchMasterReport = async () => {
        try {
            const res = await axios.get(`${API_BASE}/data-view/Employee`);
            const dbTruth = Array.isArray(res.data) ? res.data : [];
            setMasterData(dbTruth);
            setLoading(false);
        } catch (err) {
            console.error("Fetch Error:", err);
            setLoading(false);
        }
    };

    useEffect(() => {
        const filtered = masterData.filter(item => {
            const isOnLeave = item.EmpStatus === 'On Leave';
            const searchStr = filters.search.toLowerCase();
            const matchesSearch = Object.values(item).some(val => 
                val !== null && String(val).toLowerCase().includes(searchStr)
            );
            return isOnLeave && matchesSearch;
        });
        setDisplayData(filtered);
    }, [filters, masterData]);

    const handleExport = () => {
        const headers = ["Name", "Department", "Position", "Hire Date"];
        const csvRows = displayData.map(row => [
            `"${row.EmpFirstName} ${row.EmpLastName}"`,
            `"${row.DepartName}"`,
            `"${row.PosName}"`,
            `"${row.EmpHireDate}"`
        ]);
        const csvContent = ["\uFEFF" + headers.join(","), ...csvRows.map(e => e.join(","))].join("\n");
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = `On_Leave_Report_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
    };

    const groupedData = displayData.reduce((acc, curr) => {
        const dept = curr.DepartName || "Unassigned";
        if (!acc[dept]) acc[dept] = [];
        acc[dept].push(curr);
        return acc;
    }, {});

    if (loading) return <div className="h-screen flex items-center justify-center">Loading...</div>;

    return (
        <div className="min-h-screen bg-slate-50 p-6 md:p-12 font-sans text-slate-800">
            {/* Print Styles */}
            <style>{`@media print { .no-print { display: none !important; } }`}</style>

            <header className="max-w-7xl mx-auto mb-8 border-b border-slate-200 pb-8">
                <h1 className="text-3xl font-bold">On Leave Directory</h1>
                <p className="text-blue-600 font-bold text-xs uppercase">Total Personnel On Leave: {displayData.length}</p>
            </header>

            <section className="no-print max-w-7xl mx-auto mb-8 flex gap-4">
                <input 
                    type="text" 
                    placeholder="Search by name..." 
                    className="flex-1 p-3 rounded-lg border border-slate-200 text-sm"
                    onChange={e => setFilters({...filters, search: e.target.value})}
                />
                <button onClick={handleExport} className="bg-white border border-slate-200 px-6 py-3 rounded-lg text-xs font-bold uppercase hover:bg-slate-50">Export CSV</button>
                <button onClick={() => window.print()} className="bg-blue-600 text-white px-6 py-3 rounded-lg text-xs font-bold uppercase hover:bg-blue-700">Print Report</button>
            </section>

            <main className="max-w-7xl mx-auto space-y-8">
                {Object.keys(groupedData).map((dept) => (
                    <div key={dept} className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                        <div className="flex justify-between p-6 bg-slate-50 border-b border-slate-200">
                            <h2 className="text-sm font-bold text-blue-700 uppercase">{dept}</h2>
                            <span className="bg-blue-100 text-blue-800 text-[10px] font-bold px-3 py-1 rounded-full uppercase">
                                {groupedData[dept].length} Employee(s)
                            </span>
                        </div>
                        <table className="w-full text-left">
                            <thead className="text-[11px] uppercase text-slate-500 border-b">
                                <tr>
                                    <th className="p-5">Employee Name</th>
                                    <th className="p-5">Position</th>
                                    <th className="p-5">Hire Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {groupedData[dept].map((row, i) => (
                                    <tr key={i}>
                                        <td className="p-5 font-bold">{row.EmpFirstName} {row.EmpLastName}</td>
                                        <td className="p-5 text-sm">{row.PosName}</td>
                                        <td className="p-5 text-sm">{new Date(row.EmpHireDate).toLocaleDateString()}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                ))}
            </main>
        </div>
    );
};

export default Report;
