import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Sidebar from '../components/Sidebar';

const Payroll = () => {
    const [employees, setEmployees] = useState([]);
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedEmployee, setSelectedEmployee] = useState(null);
    
    // Dynamic month trackers
    const [targetPayMonth, setTargetPayMonth] = useState('May 2026'); // Month being processed
    const [filterReportMonth, setFilterReportMonth] = useState('May 2026'); // Month being viewed in report
    const [availableMonths, setAvailableMonths] = useState([]); // Loaded live from DB
    
    const [monthlyReport, setMonthlyReport] = useState([]);
    const [generatedInvoice, setGeneratedInvoice] = useState(null);

    // Initial Core Setup Data Loads
    const loadCoreData = async () => {
        try {
            const empRes = await axios.get('http://localhost:5000/api/hr/employees');
            setEmployees(empRes.data || []);
            
            const monthRes = await axios.get('http://localhost:5000/api/payroll/months/active');
            setAvailableMonths(monthRes.data || ['May 2026']);
            if (monthRes.data && monthRes.data.length > 0) {
                setFilterReportMonth(monthRes.data[0]);
            }
        } catch (err) {
            console.error("Error loading payroll dashboard modules:", err);
        }
    };

    const loadFilteredReportTable = async () => {
        try {
            const res = await axios.get(`http://localhost:5000/api/payroll/report/${filterReportMonth}`);
            setMonthlyReport(res.data || []);
        } catch (err) {
            console.error("Error charging history logs:", err);
        }
    };

    useEffect(() => { loadCoreData(); }, []);
    useEffect(() => { loadFilteredReportTable(); }, [filterReportMonth]);

    const filteredEmployees = employees.filter(emp => {
        const fullName = `${emp.firstname} ${emp.lastname}`.toLowerCase();
        return fullName.includes(searchQuery.toLowerCase());
    });

    const handleProcessPayment = async (e) => {
        e.preventDefault();
        if (!selectedEmployee) return;

        try {
            const res = await axios.post('http://localhost:5000/api/payroll/pay', {
                employeenumber: selectedEmployee.employeenumber,
                month: targetPayMonth // Process payment for any typed month
            });
            
            setGeneratedInvoice(res.data);
            alert(`Salary bill generated successfully for ${selectedEmployee.firstname} (${targetPayMonth})!`);
            
            // Reload core data to catch new dynamic months if a new one was just typed
            await loadCoreData();
            setFilterReportMonth(targetPayMonth); // Instantly snap view report table to this month
            loadFilteredReportTable();
        } catch (err) {
            alert(err.response?.data?.error || "Error running payment workflow execution.");
        }
    };

    return (
        <div className="flex bg-slate-50 min-h-screen print:bg-white">
            <div className="print:hidden"><Sidebar /></div>
            
            <main className="flex-1 p-8 print:p-0">
                <div className="mb-6 print:hidden">
                    <h1 className="text-3xl font-bold text-slate-800">Payroll Processing Hub</h1>
                    <p className="text-sm text-slate-500 mt-1">Search staff and disburse payments across any recurring monthly cycle dynamically</p>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 print:block">
                    {/* PANEL 1: STAFF SEARCH DIRECTORY */}
                    <div className="bg-white p-5 rounded-xl shadow-sm border space-y-4 h-fit print:hidden">
    <h2 className="text-xs font-bold text-slate-400 uppercase tracking-wider">🎯 1. Search Employee</h2>
    <input 
        type="text" 
        className="w-full border p-2 pl-3 rounded-lg text-sm bg-slate-50 focus:bg-white focus:outline-emerald-500 transition"
        placeholder="Type employee name to search..." 
        value={searchQuery} 
        onChange={(e) => setSearchQuery(e.target.value)}
    />
    <div className="space-y-1.5 max-h-[220px] overflow-y-auto">
        {searchQuery.trim() === "" ? (
            /* Shown when user hasn't typed anything yet */
            <div className="text-center py-6 text-slate-400 text-xs font-medium">
                <p>🔍 Start typing a worker's name to find them...</p>
            </div>
        ) : filteredEmployees.length > 0 ? (
            /* Only maps through employees if there is an active search string */
            filteredEmployees.map(emp => (
                <button
                    key={emp.employeenumber} 
                    type="button" 
                    onClick={() => { setSelectedEmployee(emp); setGeneratedInvoice(null); }}
                    className={`w-full text-left p-3 rounded-lg border text-xs transition flex flex-col gap-1 ${
                        selectedEmployee?.employeenumber === emp.employeenumber 
                            ? 'border-emerald-500 bg-emerald-50/50 font-bold' 
                            : 'border-slate-100 hover:bg-slate-50'
                    }`}
                >
                    <span className="text-slate-800 font-bold">{emp.firstname} {emp.lastname}</span>
                    <span className="text-slate-400 text-[11px]">
                        {emp.position || 'Staff'} • <span className="text-slate-500 font-medium">{emp.departmentname || 'Unassigned'}</span>
                    </span>
                </button>
            )
        )) : (
            /* Shown if they typed something but no record matches */
            <div className="text-center py-6 text-slate-400 text-xs italic">
                No matching personnel files found.
            </div>
        )}
    </div>
                    </div>

                    {/* PANEL 2: DYNAMIC PAYOUT EXECUTOR */}
                    <div className="bg-white p-5 rounded-xl shadow-sm border h-fit space-y-3 print:hidden">
                        <h2 className="text-xs font-bold text-slate-400 uppercase tracking-wider">⚙️ 2. Processing Setup</h2>
                        {selectedEmployee ? (
                            <form onSubmit={handleProcessPayment} className="space-y-4">
                                <div className="p-3 bg-slate-50 rounded-lg border text-xs space-y-1">
                                    <p className="text-slate-400 font-bold">Target Account:</p>
                                    <p className="font-bold text-sm text-slate-800">{selectedEmployee.firstname} {selectedEmployee.lastname}</p>
                                    <p className="text-slate-600 font-mono mt-1 pt-1 border-t">Net Base Payout: {Number(selectedEmployee.netsalary || 0).toLocaleString()} RWF</p>
                                </div>

                                <div>
                                    <label className="text-xs font-bold text-slate-500 uppercase">Specify Processing Month</label>
                                    <input 
                                        type="text" 
                                        className="w-full border p-2 rounded-lg mt-1 text-sm font-semibold focus:outline-emerald-500"
                                        value={targetPayMonth}
                                        onChange={(e) => setTargetPayMonth(e.target.value)}
                                        placeholder="e.g. June 2026, July 2026"
                                        required
                                    />
                                    <p className="text-[10px] text-slate-400 mt-1">Type any month/year freely. The system adapts automatically.</p>
                                </div>

                                <button type="submit" className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2 rounded-lg text-xs shadow transition">
                                    ⚡ Disburse Pay & Generate Bill
                                </button>
                            </form>
                        ) : (
                            <p className="text-xs text-slate-400 italic p-4 text-center">Select an employee from the left search directory to begin billing setup.</p>
                        )}
                    </div>

                    {/* PANEL 3: PRINTABLE BILL STUB */}
                    <div className="print:w-full">
                        {generatedInvoice && (
                            <div className="bg-white border-2 border-slate-200 rounded-xl p-5 shadow-sm space-y-4 max-w-sm mx-auto print:border-0 print:shadow-none">
                                <div className="flex justify-between border-b pb-3">
                                    <div>
                                        <h3 className="text-base font-black text-slate-800 uppercase">SmartPark Ltd</h3>
                                        <p className="text-[9px] text-slate-400 font-bold">Rubavu Operations, Rwanda</p>
                                    </div>
                                    <span className="bg-emerald-100 text-emerald-800 text-[9px] font-black px-2 py-0.5 rounded uppercase print:border">
                                        {generatedInvoice.status}
                                    </span>
                                </div>
                                <div className="space-y-1 text-xs">
                                    <p><span className="text-slate-400">Employee:</span> <strong>{generatedInvoice.employee}</strong></p>
                                    <p><span className="text-slate-400">Payment Period:</span> <strong className="text-emerald-600">{generatedInvoice.billingMonth}</strong></p>
                                    <p><span className="text-slate-400">Receipt Code:</span> <span className="font-mono text-slate-500">{generatedInvoice.transactionId}</span></p>
                                </div>
                                <div className="border-t pt-2 text-xs font-mono flex justify-between text-slate-700 bg-slate-50 p-2 rounded">
                                    <span>Net Disbursed Take-Home:</span>
                                    <span className="font-bold text-emerald-600">{Number(generatedInvoice.breakdown.netPayable).toLocaleString()} RWF</span>
                                </div>
                                <button onClick={() => window.print()} className="w-full bg-slate-900 text-white font-bold py-1.5 rounded text-xs print:hidden">
                                    🖨️ Print Verification Bill
                                </button>
                            </div>
                        )}
                    </div>
                </div>

                {/* ============================================================== */}
                {/* 📊 COMPLETELY DYNAMIC HISTORICAL LEDGER REPORT SHEET */}
                {/* ============================================================== */}
                <div className="mt-8 bg-white p-6 rounded-xl shadow-sm border print:hidden">
                    <div className="flex flex-col sm:flex-row justify-between sm:items-center gap-2 mb-4">
                        <div>
                            <h2 className="text-lg font-bold text-slate-700">Dynamic Payroll Ledger Reports</h2>
                            <p className="text-xs text-slate-400 mt-0.5">Select any historical tracking cycle from your database</p>
                        </div>
                        
                        {/* Dropdown completely built on demand from data entries in DB */}
                        <div className="bg-slate-50 px-3 py-1.5 rounded-lg border flex items-center space-x-2 w-fit">
                            <span className="text-[10px] font-bold text-slate-400 uppercase">View History:</span>
                            <select 
                                className="bg-transparent text-xs font-bold text-slate-700 outline-none cursor-pointer"
                                value={filterReportMonth}
                                onChange={(e) => setFilterReportMonth(e.target.value)}
                            >
                                {availableMonths.map(m => (
                                    <option key={m} value={m}>{m}</option>
                                ))}
                            </select>
                        </div>
                    </div>

                    <table className="w-full text-left border-collapse text-xs">
                        <thead>
                            <tr className="bg-slate-50 border-b text-slate-500 font-bold uppercase tracking-wider">
                                <th className="p-3">Staff ID</th>
                                <th className="p-3">Full Employee Name</th>
                                <th className="p-3">Department</th>
                                <th className="p-3">Gross Salary</th>
                                <th className="p-3">Deductions</th>
                                <th className="p-3 text-right">Net Paid</th>
                            </tr>
                        </thead>
                        <tbody>
                            {monthlyReport.map(reportItem => (
                                <tr key={reportItem.employeenumber} className="border-b hover:bg-slate-50 transition">
                                    <td className="p-3 font-mono text-slate-400">#{reportItem.employeenumber}</td>
                                    <td className="p-3 text-slate-800 font-bold">{reportItem.firstname} {reportItem.lastname}</td>
                                    <td className="p-3 text-slate-600">{reportItem.departmentname}</td>
                                    <td className="p-3 font-mono text-slate-600">{Number(reportItem.grosssalary).toLocaleString()} RWF</td>
                                    <td className="p-3 font-mono text-red-500">-{Number(reportItem.totaldeduction).toLocaleString()} RWF</td>
                                    <td className="p-3 font-mono text-right text-emerald-600 font-bold">{Number(reportItem.netsalary).toLocaleString()} RWF</td>
                                </tr>
                            ))}
                            {monthlyReport.length === 0 && (
                                <tr>
                                    <td colSpan="6" className="p-8 text-center text-slate-400 font-semibold italic">
                                        No payouts recorded on ledger for {filterReportMonth} cycle.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    );
};

export default Payroll;