function InactiveEmployeeList({ year }) {
    const [employees, setEmployees] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [error, setError] = React.useState(null);
    const [filter, setFilter] = React.useState('');
    const [showForm, setShowForm] = React.useState(false);
    const [editingEmployee, setEditingEmployee] = React.useState(null);

    const fetchEmployees = async () => {
        setLoading(true);
        setError(null);
        try {
            const client = window.SupabaseUtils.getClient();
            if (!client) throw new Error("Koneksi database terputus");

            const { data, error } = await client
                .from('employees')
                .select('*')
                .eq('is_active', false)
                .eq('tahun', year) // Filter year
                .order('tanggal_keluar', { ascending: false });
            
            if (error) {
                if (error.code === '42P01') {
                    throw new Error("Tabel 'employees' tidak ditemukan.");
                }
                throw error;
            }
            setEmployees(data || []);
        } catch (err) {
            console.error("Fetch Error:", err);
            setError(window.SupabaseUtils.formatError(err));
        } finally {
            setLoading(false);
        }
    };

    React.useEffect(() => {
        fetchEmployees();
    }, [year]);

    const handleEdit = (employee) => {
        setEditingEmployee(employee);
        setShowForm(true);
    };

    const handleFormSave = () => {
        setShowForm(false);
        setEditingEmployee(null);
        fetchEmployees();
    };

    const handleActivate = async (id, nama) => {
        const result = await Swal.fire({
            title: "Aktifkan Kembali?",
            text: `Pegawai "${nama}" akan dikembalikan ke status aktif.`,
            icon: "question",
            showCancelButton: true,
            confirmButtonColor: "#0f766e",
            cancelButtonColor: "#d33",
            confirmButtonText: "Ya, Aktifkan!",
            cancelButtonText: "Batal"
        });

        if (!result.isConfirmed) return;

        try {
            const client = window.SupabaseUtils.getClient();
            const { error } = await client
                .from('employees')
                .update({ 
                    is_active: true,
                    tanggal_keluar: null,
                    alasan_keluar: null
                })
                .eq('id', id);
            
            if (error) throw error;
            fetchEmployees();
            Swal.fire({
                icon: 'success',
                title: 'Berhasil Diaktifkan',
                timer: 1500,
                showConfirmButton: false
            });
        } catch (err) {
            Swal.fire("Gagal!", 'Gagal mengaktifkan kembali: ' + window.SupabaseUtils.formatError(err), "error");
        }
    };

    const filteredEmployees = employees.filter(emp => 
        (emp.nama || '').toLowerCase().includes(filter.toLowerCase()) || 
        (emp.nik || '').includes(filter) ||
        (emp.alasan_keluar || '').toLowerCase().includes(filter.toLowerCase())
    );

    return (
        <div className="p-4 md:p-8" data-name="inactive-employee-list" data-file="components/InactiveEmployeeList.js">
            <div className="mb-6">
                <h2 className="text-xl md:text-2xl font-bold text-gray-800 flex items-center gap-2">
                    <div className="icon-user-x text-red-600"></div>
                    Daftar Pegawai Non-Aktif
                </h2>
                <p className="text-sm md:text-base text-gray-500">
                    Riwayat pegawai yang sudah keluar, pensiun, atau berhenti bertugas.
                </p>
            </div>

            {error && (
                <div className="bg-red-50 text-red-600 p-4 rounded mb-6 border border-red-200">
                    <strong>Gagal memuat data:</strong> {error}
                    <div className="mt-2 text-sm text-gray-800 bg-red-100 p-2 rounded">
                        <p className="font-bold">Database perlu diupdate!</p>
                        <SqlSetupHelp />
                        <SqlUpdateKategori />
                    </div>
                </div>
            )}

            <div className="bg-white rounded-lg shadow border border-gray-200 overflow-hidden">
                <div className="p-4 border-b border-gray-200 flex items-center gap-4 bg-gray-50">
                    <div className="relative flex-1 max-w-md">
                        <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                            <div className="icon-search text-lg"></div>
                        </div>
                        <input 
                            type="text" 
                            placeholder="Cari berdasarkan Nama, NIK, atau Alasan..."
                            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-red-500"
                            value={filter}
                            onChange={(e) => setFilter(e.target.value)}
                        />
                    </div>
                </div>

                {/* Desktop Table View */}
                <div className="hidden md:block overflow-x-auto">
                    <table className="w-full text-sm text-left">
                        <thead className="bg-red-50 text-red-900 font-medium border-b border-red-100">
                            <tr>
                                <th className="px-6 py-3 w-12">No</th>
                                <th className="px-6 py-3">Nama Pegawai</th>
                                <th className="px-6 py-3">NIK</th>
                                <th className="px-6 py-3">Tanggal Keluar</th>
                                <th className="px-6 py-3">Alasan Keluar</th>
                                <th className="px-6 py-3 text-right">Aksi</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-200">
                            {loading ? (
                                <tr>
                                    <td colSpan="6" className="px-6 py-8 text-center text-gray-500">
                                        <div className="inline-block animate-spin w-6 h-6 border-2 border-red-500 border-t-transparent rounded-full mb-2"></div>
                                        <div>Memuat data...</div>
                                    </td>
                                </tr>
                            ) : filteredEmployees.length === 0 ? (
                                <tr>
                                    <td colSpan="6" className="px-6 py-8 text-center text-gray-500">
                                        Tidak ada data pegawai non-aktif.
                                    </td>
                                </tr>
                            ) : (
                                filteredEmployees.map((emp, index) => (
                                    <tr key={emp.id} className="hover:bg-gray-50 bg-gray-50">
                                        <td className="px-6 py-3 text-gray-400">{index + 1}</td>
                                        <td className="px-6 py-3 font-medium text-gray-700">{emp.nama}</td>
                                        <td className="px-6 py-3 font-mono text-xs text-gray-500">{emp.nik}</td>
                                        <td className="px-6 py-3 text-red-600 font-medium">
                                            {emp.tanggal_keluar ? new Date(emp.tanggal_keluar).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }) : '-'}
                                        </td>
                                        <td className="px-6 py-3">
                                            <span className="bg-red-100 text-red-800 px-2 py-1 rounded text-xs">
                                                {emp.alasan_keluar || 'Tidak disebutkan'}
                                            </span>
                                        </td>
                                        <td className="px-6 py-3 text-right space-x-2">
                                            <button 
                                                onClick={() => handleActivate(emp.id, emp.nama)}
                                                className="text-green-600 hover:text-green-800 transition-colors"
                                                title="Aktifkan Kembali"
                                            >
                                                <div className="icon-rotate-ccw text-lg"></div>
                                            </button>
                                            <button 
                                                onClick={() => handleEdit(emp)}
                                                className="text-blue-600 hover:text-blue-800 transition-colors"
                                                title="Edit Data"
                                            >
                                                <div className="icon-pencil text-lg"></div>
                                            </button>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Mobile Card View */}
                <div className="md:hidden">
                    {loading ? (
                        <div className="p-8 text-center text-gray-500">
                            <div className="inline-block animate-spin w-8 h-8 border-4 border-red-500 border-t-transparent rounded-full mb-3"></div>
                            <div>Memuat data...</div>
                        </div>
                    ) : filteredEmployees.length === 0 ? (
                        <div className="p-8 text-center text-gray-500">
                            Tidak ada data pegawai non-aktif.
                        </div>
                    ) : (
                        <div className="bg-gray-50 p-4 space-y-4">
                            {filteredEmployees.map((emp) => (
                                <div key={emp.id} className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                                    <div className="flex justify-between items-start mb-3">
                                        <div>
                                            <div className="font-bold text-gray-800 text-lg leading-tight">{emp.nama}</div>
                                            <div className="text-xs text-gray-500 font-mono mt-1">NIK: {emp.nik || '-'}</div>
                                        </div>
                                        <span className="bg-red-100 text-red-800 text-[10px] px-2 py-1 rounded font-bold uppercase tracking-wide">
                                            Non-Aktif
                                        </span>
                                    </div>
                                    
                                    <div className="bg-red-50 p-3 rounded-lg text-xs mb-4 border border-red-100">
                                        <div className="grid grid-cols-1 gap-2">
                                            <div className="flex justify-between border-b border-red-200/50 pb-2">
                                                <span className="text-red-400 font-bold uppercase">Tanggal Keluar</span>
                                                <span className="font-bold text-red-900">
                                                    {emp.tanggal_keluar ? new Date(emp.tanggal_keluar).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }) : '-'}
                                                </span>
                                            </div>
                                            <div className="flex justify-between pt-1">
                                                <span className="text-red-400 font-bold uppercase">Alasan</span>
                                                <span className="font-bold text-red-900 text-right">
                                                    {emp.alasan_keluar || '-'}
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="flex gap-2">
                                        <button 
                                            onClick={() => handleActivate(emp.id, emp.nama)}
                                            className="flex-1 bg-white border border-green-200 text-green-700 hover:bg-green-50 px-3 py-2 rounded text-xs font-bold flex items-center justify-center gap-1 transition-colors shadow-sm"
                                        >
                                            <div className="icon-rotate-ccw text-sm"></div> Aktifkan
                                        </button>
                                        <button 
                                            onClick={() => handleEdit(emp)}
                                            className="flex-1 bg-white border border-blue-200 text-blue-700 hover:bg-blue-50 px-3 py-2 rounded text-xs font-bold flex items-center justify-center gap-1 transition-colors shadow-sm"
                                        >
                                            <div className="icon-pencil text-sm"></div> Edit
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>

            {showForm && (
                <EmployeeForm 
                    employee={editingEmployee} 
                    onSave={handleFormSave} 
                    onCancel={() => { setShowForm(false); setEditingEmployee(null); }} 
                />
            )}
        </div>
    );
}