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

const Salary = () => {
    const [brackets, setBrackets] = useState([]);
    const [grossSalary, setGrossSalary] = useState('');
    const [totalDeduction, setTotalDeduction] = useState('');
    const [month, setMonth] = useState('May 2026');
    
    // UI Operational Tracker State
    const [isEditing, setIsEditing] = useState(false);

    const fetchBrackets = async () => {
        try {
            const res = await axios.get('http://localhost:5000/api/payroll');
            setBrackets(res.data);
        } catch (err) {
            console.error("Error loading salary structure tiers:", err);
        }
    };

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

    const handleSaveBracket = async (e) => {
        e.preventDefault();

        // Basic frontend validation rule checklist
        if (Number(totalDeduction) > Number(grossSalary)) {
            alert("Warning: Deductions cannot exceed Gross Salary values!");
            return;
        }

        const payload = {
            grosssalary: Number(grossSalary),
            totaldeduction: Number(totalDeduction),
            month: month
        };

        try {
            if (isEditing) {
                // [UPDATE] - Runs update against the base parameter identifier
                await axios.put(`http://localhost:5000/api/payroll/${grossSalary}`, payload);
                alert("Salary bracket structural tier adjusted successfully!");
            } else {
                // [CREATE] - Insert a brand new structural financial rule row
                await axios.post('http://localhost:5000/api/payroll', payload);
                alert("New salary matrix scale bracket formulated successfully!");
            }
            resetForm();
            fetchBrackets();
        } catch (err) {
            alert(err.response?.data?.error || "Failed to finalize salary configuration updates.");
        }
    };

    const startEditMode = (bracket) => {
        setIsEditing(true);
        setGrossSalary(bracket.grosssalary); // Primary key element is locked down as reference
        setTotalDeduction(bracket.totaldeduction);
        setMonth(bracket.month || 'May 2026');
    };

    const handleDeleteBracket = async (grossKey) => {
        if (window.confirm(`Are you sure you want to permanently delete the ${Number(grossKey).toLocaleString()} RWF salary tier bracket?`)) {
            try {
                const res = await axios.delete(`http://localhost:5000/api/payroll/${grossKey}`);
                alert(res.data.message || "Salary tier configuration removed cleanly.");
                if (grossSalary === grossKey) resetForm();
                fetchBrackets();
            } catch (err) {
                alert(err.response?.data?.error || "Cannot drop baseline structural values. Ensure no active department depends on this gross rule tier.");
            }
        }
    };

    const resetForm = () => {
        setIsEditing(false);
        setGrossSalary('');
        setTotalDeduction('');
        setMonth('May 2026');
    };

    return (
        <div className="flex bg-slate-50 min-h-screen">
            <Sidebar />
            <main className="flex-1 p-8">
                <div className="mb-6">
                    <h1 className="text-3xl font-bold text-slate-800">Compensation Matrix Scales</h1>
                    <p className="text-sm text-slate-500 mt-1">Configure global standard corporate pay scales, tax brackets, and withholding tiers</p>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    {/* ⚙️ BRACKET BUILDER FORM PANEL */}
                    <form onSubmit={handleSaveBracket} className="bg-white p-6 rounded-xl shadow-sm border h-fit space-y-4">
                        <div className="flex justify-between items-center border-b pb-2">
                            <h2 className="text-lg font-bold text-slate-700">
                                {isEditing ? "⚙️ Modify Scale Rules" : "🆕 Formulate Pay Scale"}
                            </h2>
                            {isEditing && (
                                <button type="button" onClick={resetForm} className="text-xs bg-slate-100 hover:bg-slate-200 text-slate-600 px-2 py-1 rounded font-medium">
                                    Cancel
                                </button>
                            )}
                        </div>

                        <div>
                            <label className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Gross Base Salary (RWF)</label>
                            <input 
                                type="number" 
                                className={`w-full border p-2 rounded mt-1 text-sm font-mono ${isEditing ? 'bg-slate-100 text-slate-500 cursor-not-allowed' : 'focus:outline-emerald-500'}`} 
                                value={grossSalary} 
                                onChange={e => setGrossSalary(e.target.value)} 
                                placeholder="e.g. 600000"
                                disabled={isEditing} // Primary Key criteria indicator remains locked during update edits
                                required 
                            />
                        </div>

                        <div>
                            <label className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Total Deductions (RSSB / Taxes)</label>
                            <input 
                                type="number" 
                                className="w-full border p-2 rounded mt-1 text-sm font-mono focus:outline-emerald-500" 
                                value={totalDeduction} 
                                onChange={e => setTotalDeduction(e.target.value)} 
                                placeholder="e.g. 55000"
                                required 
                            />
                        </div>

                        <div>
                            <label className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Applicable Cycle Month</label>
                            <input 
                                type="text" 
                                className="w-full border p-2 rounded mt-1 text-sm focus:outline-emerald-500" 
                                value={month} 
                                onChange={e => setMonth(e.target.value)} 
                                required 
                            />
                        </div>

                        {/* Automated Realtime Mathematical Calculation Display Box */}
                        {grossSalary && totalDeduction && (
                            <div className="bg-slate-50 p-3 rounded-lg border border-dashed text-xs space-y-1">
                                <div className="flex justify-between text-slate-500">
                                    <span>Base Gross:</span>
                                    <span>{Number(grossSalary).toLocaleString()} RWF</span>
                                </div>
                                <div className="flex justify-between text-red-500">
                                    <span>Withholdings:</span>
                                    <span>-{Number(totalDeduction).toLocaleString()} RWF</span>
                               </div>
                                <div className="flex justify-between text-emerald-600 font-bold border-t pt-1 mt-1 text-sm">
                                    <span>Est Take-Home Net:</span>
                                    <span>{(Number(grossSalary) - Number(totalDeduction)).toLocaleString()} RWF</span>
                                </div>
                            </div>
                        )}

                        <button type="submit" className={`w-full text-white py-2.5 rounded-lg font-semibold transition tracking-wide ${isEditing ? 'bg-amber-500 hover:bg-amber-600' : 'bg-slate-800 hover:bg-slate-900'}`}>
                            {isEditing ? "Update Tier Matrix Properties" : "Formulate Scale Rule"}
                        </button>
                    </form>

                    {/* 📊 INTERACTIVE COMPENSATION LEDGER SHEET */}
                    <div className="lg:col-span-2 bg-white p-6 rounded-xl shadow-sm border overflow-x-auto">
                        <h2 className="text-lg font-bold text-slate-700 mb-4">Active System Financial Scales</h2>
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr className="bg-slate-50 border-b text-slate-600 text-xs font-bold uppercase tracking-wider">
                                    <th className="p-3">Gross Category Base</th>
                                    <th className="p-3">Deduction Cap</th>
                                    <th className="p-3">Computed Net Payable</th>
                                    <th className="p-3 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {brackets.map(b => (
                                    <tr key={b.grosssalary} className="border-b hover:bg-slate-50 text-sm transition">
                                        <td className="p-3 font-mono font-bold text-slate-800">
                                            {Number(b.grosssalary).toLocaleString()} RWF
                                        </td>
                                        <td className="p-3 font-mono text-red-500 font-medium">
                                            {Number(b.totaldeduction).toLocaleString()} RWF
                                        </td>
                                        <td className="p-3 font-mono text-emerald-600 font-bold">
                                            {Number(b.netsalary).toLocaleString()} RWF
                                        </td>
                                        <td className="p-3 flex space-x-1 justify-center items-center">
                                            <button 
                                                onClick={() => startEditMode(b)}
                                                className="text-xs bg-amber-50 text-amber-700 font-semibold px-2.5 py-1.5 rounded border border-amber-200 hover:bg-amber-100 transition"
                                            >
                                                ✏️ Adjust
                                            </button>
                                            <button 
                                                onClick={() => handleDeleteBracket(b.grosssalary)}
                                                className="text-xs bg-red-50 text-red-700 font-semibold px-2.5 py-1.5 rounded border border-red-200 hover:bg-red-100 transition"
                                            >
                                                🗑️ Purge
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                                {brackets.length === 0 && (
                                    <tr>
                                        <td colSpan="4" className="p-8 text-center text-slate-400 font-medium">No system matrix brackets found. Create your base pay rulesets first.</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        </div>
    );
};

export default Salary;