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

const Employees = () => {
    const [employees, setEmployees] = useState([]);
    const [departments, setDepartments] = useState([]);
    
    // Form management state structure
    const [form, setForm] = useState({
        firstname: '', lastname: '', position: '', address: '', telephone: '', gender: 'M', hireddate: '', departmentnumber: ''
    });
    
    // Tracking active CRUD operational states
    const [isEditing, setIsEditing] = useState(false);
    const [editTargetId, setEditTargetId] = useState(null);

    const loadData = async () => {
        try {
            const empRes = await axios.get('http://localhost:5000/api/hr/employees');
            const deptRes = await axios.get('http://localhost:5000/api/hr/departments');
            setEmployees(empRes.data);
            setDepartments(deptRes.data);
        } catch (err) { 
            console.error("Error loading HR records:", err); 
        }
    };

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

    // Form submission handler (Handles both Insert and Update actions)
    const handleFormSubmit = async (e) => {
        e.preventDefault();
        try {
            if (isEditing) {
                // Execute [UPDATE] request
                await axios.put(`http://localhost:5000/api/hr/employees/${editTargetId}`, form);
                alert("Staff profile updated successfully!");
            } else {
                // Execute [CREATE] request
                await axios.post('http://localhost:5000/api/hr/employees', form);
                alert("New staff member enrolled safely!");
            }
            resetFormState();
            loadData();
        } catch (err) { 
            alert(err.response?.data?.error || "Operation failed. Check server status logs."); 
        }
    };

    // Populates inputs to initiate edit mode
    const startEditMode = (emp) => {
        setIsEditing(true);
        setEditTargetId(emp.employeenumber);
        
        // Format date string correctly (YYYY-MM-DD) for HTML5 input field matching
        const cleanDate = emp.hireddate ? emp.hireddate.split('T')[0] : '';

        setForm({
            firstname: emp.firstname || '',
            lastname: emp.lastname || '',
            position: emp.position || '',
            address: emp.address || '',
            telephone: emp.telephone || '',
            gender: emp.gender || 'M',
            hireddate: cleanDate,
            departmentnumber: emp.departmentnumber || ''
        });
    };

    // Drops an individual record
    const handleDeleteEmployee = async (id, name) => {
        if (window.confirm(`Are you absolutely sure you want to delete the file profile for ${name}?`)) {
            try {
                await axios.delete(`http://localhost:5000/api/hr/employees/${id}`);
                alert("Personnel profile deleted cleanly from ledger directory.");
                if(editTargetId === id) resetFormState();
                loadData();
            } catch (err) {
                alert("Failed to delete records.");
            }
        }
    };

    const resetFormState = () => {
        setIsEditing(false);
        setEditTargetId(null);
        setForm({ firstname: '', lastname: '', position: '', address: '', telephone: '', gender: 'M', hireddate: '', departmentnumber: '' });
    };

    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">HR Staff File Registration</h1>
                    <p className="text-sm text-slate-500 mt-1">Manage corporate personnel records and operational assignments</p>
                </div>

                <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
                    {/* Data-Entry Intake Panel */}
                    <form onSubmit={handleFormSubmit} className="bg-white p-6 rounded-xl shadow-sm border space-y-3 h-fit">
                        <div className="flex justify-between items-center border-b pb-2">
                            <h2 className="text-lg font-bold text-slate-700">
                                {isEditing ? "⚙️ Edit Staff Profile" : "Digital Intake Card"}
                            </h2>
                            {isEditing && (
                                <button type="button" onClick={resetFormState} className="text-xs bg-slate-100 hover:bg-slate-200 text-slate-600 px-2 py-1 rounded font-medium">
                                    Cancel
                                </button>
                            )}
                        </div>

                        <div className="grid grid-cols-2 gap-2">
                            <div>
                                <label className="text-xs font-semibold text-slate-500">First Name</label>
                                <input type="text" className="w-full border p-1.5 text-sm rounded mt-1 focus:outline-emerald-500" value={form.firstname} onChange={e=>setForm({...form, firstname: e.target.value})} required />
                            </div>
                            <div>
                                <label className="text-xs font-semibold text-slate-500">Last Name</label>
                                <input type="text" className="w-full border p-1.5 text-sm rounded mt-1 focus:outline-emerald-500" value={form.lastname} onChange={e=>setForm({...form, lastname: e.target.value})} required />
                            </div>
                        </div>
                        <div>
                            <label className="text-xs font-semibold text-slate-500">Corporate Position Title</label>
                            <input type="text" className="w-full border p-1.5 text-sm rounded mt-1 focus:outline-emerald-500" value={form.position} onChange={e=>setForm({...form, position: e.target.value})} placeholder="e.g. Yard Inspector" required />
                        </div>
                        <div>
                            <label className="text-xs font-semibold text-slate-500">Mobile Phone Line</label>
                            <input type="text" className="w-full border p-1.5 text-sm rounded mt-1 focus:outline-emerald-500" value={form.telephone} onChange={e=>setForm({...form, telephone: e.target.value})} required />
                        </div>
                        <div>
                            <label className="text-xs font-semibold text-slate-500">Residential Address</label>
                            <input type="text" className="w-full border p-1.5 text-sm rounded mt-1 focus:outline-emerald-500" value={form.address} onChange={e=>setForm({...form, address: e.target.value})} placeholder="Rubavu, Western Province" required />
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                            <div>
                                <label className="text-xs font-semibold text-slate-500">Gender</label>
                                <select className="w-full border p-1.5 text-sm rounded mt-1 bg-white focus:outline-emerald-500" value={form.gender} onChange={e=>setForm({...form, gender: e.target.value})}>
                                    <option value="M">Male</option>
                                    <option value="F">Female</option>
                                </select>
                            </div>
                            <div>
                                <label className="text-xs font-semibold text-slate-500">Hired Date</label>
                                <input type="date" className="w-full border p-1.5 text-sm rounded mt-1 focus:outline-emerald-500" value={form.hireddate} onChange={e=>setForm({...form, hireddate: e.target.value})} required />
                            </div>
                        </div>
                        <div>
                            <label className="text-xs font-semibold text-slate-500">Assign Department</label>
                            <select className="w-full border p-1.5 text-sm rounded mt-1 bg-white focus:outline-emerald-500" value={form.departmentnumber} onChange={e=>setForm({...form, departmentnumber: e.target.value})} required>
                                className="w-full border p-1.5 text-sm rounded mt-1 bg-white focus:outline-emerald-500" 
    value={form.departmentnumber} 
    onChange={e => setForm({...form, departmentnumber: e.target.value})} 
    required

    <option value="">Select Assignment Option</option>
    {departments.map(d => (
        // MUST use d.departmentnumber for the value, and d.departmentname for the text
        <option key={d.departmentnumber} value={d.departmentnumber}>
            {d.departmentname} ({d.departmentnumber})
        </option>
    ))}
                            </select>
                        </div>
                        
                        <button type="submit" className={`w-full text-white py-2 rounded-lg font-semibold transition mt-2 tracking-wide ${isEditing ? 'bg-amber-500 hover:bg-amber-600' : 'bg-emerald-600 hover:bg-emerald-700'}`}>
                            {isEditing ? "Save Modifications" : "Enroll Employee"}
                        </button>
                    </form>

                    {/* Workforce Directory Spreadsheet */}
                    <div className="xl: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">Registered Personnel Roster</h2>
                        <table className="w-full text-left border-collapse text-sm">
                            <thead>
                                <tr className="bg-slate-50 border-b text-slate-600 font-bold text-xs uppercase tracking-wider">
                                    <th className="p-3">ID</th>
                                    <th className="p-3">Staff Name</th>
                                    <th className="p-3">Position</th>
                                    <th className="p-3">Department</th>
                                    <th className="p-3 text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {employees.map(emp => (
                                    <tr key={emp.employeenumber} className="border-b hover:bg-slate-50 transition">
                                        <td className="p-3 font-mono text-xs text-slate-400 font-bold">#{emp.employeenumber}</td>
                                        <td className="p-3 font-semibold text-slate-800">{emp.firstname} {emp.lastname}</td>
                                        <td className="p-3 text-slate-500 text-xs font-medium">{emp.position}</td>
                                        <td className="p-3">
                                            <span className="px-2 py-0.5 text-xs font-bold bg-blue-50 text-blue-700 border border-blue-100 rounded-md">
                                                {emp.departmentname || 'Unassigned'}
                                            </span>
                                        </td>
                                        <td className="p-3 flex space-x-1 justify-center items-center">
                                            <button 
                                                onClick={() => startEditMode(emp)}
                                                className="text-xs bg-amber-50 text-amber-700 border border-amber-200 px-2 py-1 rounded font-medium hover:bg-amber-100 transition"
                                            >
                                                ✏️ Edit
                                            </button>
                                            <button 
                                                onClick={() => handleDeleteEmployee(emp.employeenumber, `${emp.firstname} ${emp.lastname}`)}
                                                className="text-xs bg-red-50 text-red-700 border border-red-200 px-2 py-1 rounded font-medium hover:bg-red-100 transition"
                                            >
                                                🗑️ Delete
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                                {employees.length === 0 && (
                                    <tr>
                                        <td colSpan="5" className="p-8 text-center text-slate-400 font-medium">No personnel file entries found.</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        </div>
    );
};

export default Employees;