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

const Departments = () => {
    const [departments, setDepartments] = useState([]);
    const [salaryBrackets, setSalaryBrackets] = useState([]); // System pay grades matrix
    
    // Form element control states
    const [code, setCode] = useState('');
    const [name, setName] = useState('');
    const [gross, setGross] = useState('');
    const [autoDeduction, setAutoDeduction] = useState(0);
    const [autoNet, setAutoNet] = useState(0);
    
    const [isEditing, setIsEditing] = useState(false);

    const loadPageData = async () => {
        try {
            const deptRes = await axios.get('http://localhost:5000/api/hr/departments');
            const salaryRes = await axios.get('http://localhost:5000/api/payroll');
            setDepartments(deptRes.data);
            setSalaryBrackets(salaryRes.data);
        } catch (err) {
            console.error("Error loading structural baseline resources:", err);
        }
    };

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

    // Monitor Gross Salary selection input changes to pull matching deductions automatically
    useEffect(() => {
        const matchedBracket = salaryBrackets.find(b => Number(b.grosssalary) === Number(gross));
        if (matchedBracket) {
            setAutoDeduction(Number(matchedBracket.totaldeduction));
            setAutoNet(Number(matchedBracket.netsalary));
        } else {
            setAutoDeduction(0);
            setAutoNet(0);
        }
    }, [gross, salaryBrackets]);

    const handleSaveDepartment = async (e) => {
        e.preventDefault();
        
        const payload = {
            departmentnumber: code,
            departmentname: name,
            grosssalary: Number(gross)
        };

        try {
            const res = await axios.post('http://localhost:5000/api/hr/departments', payload);
            alert(res.data.message || "Saved successfully!");
            resetForm();
            loadPageData();
        } catch (err) {
            // Displays your customized validation alert notification window
            alert(err.response?.data?.error || "Error processing data parameters entry updates.");
        }
    };

    const startEditMode = (dept) => {
        setIsEditing(true);
        setCode(dept.departmentnumber);
        setName(dept.departmentname);
        setGross(dept.grosssalary || '');
    };

    const handleDeleteDepartment = async (id) => {
        if (window.confirm(`Permanently remove Department ${id}?`)) {
            try {
                await axios.delete(`http://localhost:5000/api/hr/departments/${id}`);
                loadPageData();
            } catch (err) { alert("Failed to clear element profile."); }
        }
    };

    const resetForm = () => {
        setIsEditing(false);
        setCode('');
        setName('');
        setGross('');
    };

    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">Department Management</h1>
                    <p className="text-sm text-slate-500 mt-1">Assign functional branches to automated corporate pay brackets</p>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    {/* 🏢 REGISTER / MANAGE DIVISION STRUCTURAL FORM PANEL */}
                    <form onSubmit={handleSaveDepartment} 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 ? "⚙️ Edit Division Profile" : "🆕 New Department Setup"}
                            </h2>
                        </div>

                        <div>
                            <label className="text-xs font-semibold text-slate-500 uppercase">Dept Code</label>
                            <input 
                                type="text" 
                                className={`w-full border p-2 rounded mt-1 text-sm font-mono ${isEditing ? 'bg-slate-100 text-slate-400 cursor-not-allowed' : 'focus:outline-emerald-500'}`} 
                                value={code} onChange={e => setCode(e.target.value)} placeholder="e.g. INF-04" disabled={isEditing} required 
                            />
                        </div>

                        <div>
                            <label className="text-xs font-semibold text-slate-500 uppercase">Department Name</label>
                            <input type="text" className="w-full border p-2 rounded mt-1 text-sm focus:outline-emerald-500" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Tech Support Operations" required />
                        </div>

                        {/* Gross Salary Input linked to lookup matrix detection system alerts */}
                        <div>
                            <label className="text-xs font-semibold text-slate-500 uppercase">Link Gross Scale Tier (RWF)</label>
                            <input 
                                type="number" 
                                className="w-full border p-2 rounded mt-1 text-sm font-mono focus:outline-emerald-500" 
                                value={gross} 
                                onChange={e => setGross(e.target.value)} 
                                placeholder="Type or Select Pay Bracket Scale" 
                                list="salary-options" // Provides helper suggestions from active database entries
                                required 
                            />
                            <datalist id="salary-options">
                                {salaryBrackets.map(b => (
                                    <option key={b.grosssalary} value={b.grosssalary} />
                                ))}
                            </datalist>
                        </div>

                        {/* Dynamic Deduction Summary Block */}
                        {gross && (
                            <div className={`p-3 rounded-lg border border-dashed text-xs space-y-1 transition ${autoDeduction > 0 ? 'bg-emerald-50/50 border-emerald-200' : 'bg-red-50 border-red-200'}`}>
                                {autoDeduction > 0 ? (
                                    <>
                                        <div className="flex justify-between text-slate-600">
                                            <span>📉 Linked Deduction:</span>
                                            <span className="font-bold text-red-500">-{autoDeduction.toLocaleString()} RWF</span>
                                        </div>
                                        <div className="flex justify-between border-t pt-1 font-bold text-emerald-700">
                                            <span>💰 Calculated Net Take-Home:</span>
                                            <span>{autoNet.toLocaleString()} RWF</span>
                                        </div>
                                    </>
                                ) : (
                                    <p className="text-red-600 font-semibold flex items-center gap-1">
                                        ⚠️ Warning: Unknown pay grade. Submission will trigger a system rejection notification.
                                    </p>
                                )}
                            </div>
                        )}

                        <button type="submit" className="w-full bg-slate-900 hover:bg-slate-800 text-white py-2.5 rounded-lg font-semibold text-sm tracking-wide transition">
                            Finalize Structural Link
                        </button>
                    </form>

                    {/* REPORT TABLE VIEW */}
                    <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 Infrastructure Units</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">Code</th>
                                    <th className="p-3">Division Name</th>
                                    <th className="p-3">Gross Cap</th>
                                    <th className="p-3">Deductions</th>
                                    <th className="p-3 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {departments.map(dept => (
                                    <tr key={dept.departmentnumber} className="border-b hover:bg-slate-50 text-sm transition">
                                        <td className="p-3 font-mono font-bold text-slate-800">{dept.departmentnumber}</td>
                                        <td className="p-3 font-medium text-slate-700">{dept.departmentname}</td>
                                        <td className="p-3 font-mono text-slate-600 font-semibold">{Number(dept.grosssalary).toLocaleString()} RWF</td>
                                        <td className="p-3 font-mono text-red-500">-{Number(dept.totaldeduction).toLocaleString()} RWF</td>
                                        <td className="p-3 flex space-x-1 justify-center items-center">
                                            <button onClick={() => startEditMode(dept)} className="text-xs bg-amber-50 text-amber-700 border border-amber-200 px-2.5 py-1 rounded hover:bg-amber-100 transition">✏️ Edit</button>
                                            <button onClick={() => handleDeleteDepartment(dept.departmentnumber)} className="text-xs bg-red-50 text-red-700 border border-red-200 px-2.5 py-1 rounded hover:bg-red-100 transition">🗑️ Delete</button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        </div>
    );
};

export default Departments;