import React, { useState, useEffect } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faPlusCircle, faEdit, faTrash, faExclamationTriangle, faTimes, faUserGraduate
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';

// ========================================================================
// --- Komponen Bantuan: Modal Konfirmasi Hapus Kustom ---
// ========================================================================
const DeleteConfirmationModal = ({ isOpen, onClose, onConfirm, item }) => {
    if (!isOpen || !item) return null;

    return (
        <div className="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 p-4 transition-opacity duration-300">
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 scale-100 opacity-100">
                {/* Header */}
                <div className="p-6 border-b border-gray-100 flex justify-between items-center bg-red-50 rounded-t-xl">
                    <h3 className="text-xl font-bold text-red-700 flex items-center">
                        <FontAwesomeIcon icon={faExclamationTriangle} className="mr-3 w-5 h-5" />
                        Konfirmasi Penghapusan Pendaftar
                    </h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600 transition">
                        <FontAwesomeIcon icon={faTimes} className="w-5 h-5" />
                    </button>
                </div>

                {/* Body */}
                <div className="p-6">
                    <p className="text-gray-700">
                        Anda yakin ingin menghapus data pendaftar **"{item.nama}"** dari Jurusan **"{item.jurusan}"**?
                    </p>
                    <p className="text-gray-700 mt-2 font-semibold text-red-600">
                        Data yang dihapus tidak dapat dikembalikan.
                    </p>
                </div>

                {/* Footer */}
                <div className="p-6 border-t border-gray-100 flex justify-end space-x-3 rounded-b-xl">
                    <button onClick={onClose} className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300 transition duration-150">
                        Batal
                    </button>
                    <button onClick={onConfirm} className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition duration-150">
                        Ya, Hapus
                    </button>
                </div>
            </div>
        </div>
    );
};

// ========================================================================
// --- Komponen Utama: Pendaftaran Mahasiswa PO Index Page ---
// ========================================================================
/**
 * @param {object} props
 * @param {object} props.auth
 * @param {array} [props.pendaftar=[]] - Daftar Pendaftar Online Kampus.
 */
export default function PendaftaranMahasiswaPOIndex({ auth, pendaftar = [] }) {
    const { flash } = usePage().props;
    
    // Pengecekan aman data
    const listPendaftar = Array.isArray(pendaftar) ? pendaftar : []; 
    
    // State untuk Modal Hapus
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [itemToDelete, setItemToDelete] = useState(null);

    // Tampilkan SweetAlert jika ada flash message sukses/error
    useEffect(() => {
        if (flash && flash.success) { 
            Swal.fire('Berhasil!', flash.success, 'success');
        } else if (flash && flash.error) { 
            Swal.fire('Gagal!', flash.error, 'error');
        }
    }, [flash]);

    // --- CRUD Handlers ---
    const handleDeleteClick = (item) => { 
        setItemToDelete(item); 
        setIsModalOpen(true);
    };

    const handleConfirmDelete = () => {
        if (itemToDelete) {
            router.delete(route('admin.kampus.pendaftaranPO.destroy', itemToDelete.id), {
                preserveScroll: true,
                onSuccess: () => {
                    setIsModalOpen(false);
                    setItemToDelete(null);
                },
                onError: (errors) => {
                    console.error("Gagal menghapus Pendaftar:", errors);
                    setIsModalOpen(false);
                    Swal.fire('Gagal!', 'Terjadi kesalahan saat menghapus data.', 'error');
                },
            });
        }
    };
    
    const hasItems = listPendaftar.length > 0;

    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Manajemen Pendaftaran Mahasiswa Online</h2>}
        >
            <Head title="Pendaftar Mahasiswa Online" />

            {/* Modal Konfirmasi Delete */}
            <DeleteConfirmationModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onConfirm={handleConfirmDelete}
                item={itemToDelete}
            />

            <div className="max-w-7xl mx-auto sm:px-6 lg:px-8 py-12">
                <div className="bg-white overflow-hidden shadow-xl sm:rounded-xl p-6">
                    <h3 className="text-2xl font-bold text-gray-800 mb-6 flex items-center">
                        <FontAwesomeIcon icon={faUserGraduate} className="mr-3 text-emerald-600" />
                        Daftar Pendaftar Mahasiswa Online
                    </h3>

                    {/* Header dan Tombol Tambah Baru */}
                    {/* <div className="flex justify-between items-center mb-6">
                        <div className="text-gray-500 italic text-sm">Total: {listPendaftar.length} Pendaftar</div>
                        <Link
                            href={route('admin.kampus.pendaftaranPO.create')} 
                            className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg font-semibold text-xs uppercase tracking-widest transition ease-in-out duration-150 shadow-md justify-center bg-emerald-600 text-white hover:bg-emerald-700 active:bg-emerald-900 focus:outline-none focus:border-emerald-900 focus:ring ring-emerald-300"
                        >
                            <FontAwesomeIcon icon={faPlusCircle} className="w-4 h-4 mr-2" />
                            Tambah Pendaftar Baru
                        </Link>
                    </div> */}

                    {/* Table Data Pendaftar */}
                    <div className="overflow-x-auto rounded-lg shadow-lg border border-gray-200">
                        <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                                <tr>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/12">Nama</th> 
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/12">Email / HP</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-2/12">Jurusan</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-1/12">Angkatan</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-2/12">Status</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-2/12">Aksi</th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {hasItems ? (
                                    listPendaftar.map((item) => (
                                        <tr key={item.id} className="hover:bg-gray-50 transition duration-100">
                                            {/* Nama */}
                                            <td className="px-6 py-4 text-sm font-semibold text-gray-900">{item.nama}</td>

                                            {/* Email / HP */}
                                            <td className="px-6 py-4 text-sm text-gray-700">
                                                {item.email_pribadi}
                                                <div className="text-xs text-gray-500 mt-1">HP: {item.no_hp}</div>
                                            </td>

                                            {/* Jurusan */}
                                            <td className="px-6 py-4 text-sm text-gray-700">{item.jurusan} ({item.program_kuliah})</td>

                                            {/* Angkatan */}
                                            <td className="px-6 py-4 text-sm text-gray-500 text-center">{item.angkatan}</td>

                                            {/* Status */}
                                            <td className="px-6 py-4 text-sm text-center">
                                                <span className={`px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                                                    item.status_mahasiswa === 'Mahasiswa Baru' ? 'bg-green-100 text-green-800' :
                                                    item.status_mahasiswa === 'Transfer' || item.status_mahasiswa === 'Pindah Kampus' ? 'bg-yellow-100 text-yellow-800' :
                                                    'bg-blue-100 text-blue-800'
                                                }`}>
                                                    {item.status_mahasiswa}
                                                </span>
                                            </td>

                                            {/* Aksi */}
                                            <td className="px-6 py-4 text-center text-sm font-medium">
                                                <div className="flex justify-center space-x-2">
                                                    {/* Tombol Edit */}
                                                    <Link
                                                        href={route('admin.kampus.pendaftaranPO.edit', item.id)}
                                                        className="transition duration-150 p-2 rounded-full text-blue-600 hover:text-blue-900 hover:bg-blue-100"
                                                        title="Edit Data Pendaftar"
                                                    >
                                                        <FontAwesomeIcon icon={faEdit} className="w-4 h-4" />
                                                    </Link>

                                                    {/* Tombol Hapus */}
                                                    <button
                                                        onClick={() => handleDeleteClick(item)} 
                                                        className="transition duration-150 p-2 rounded-full text-red-600 hover:text-red-900 hover:bg-red-100"
                                                        title="Hapus Data Pendaftar"
                                                    >
                                                        <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="6" className="px-6 py-8 text-center text-gray-500 italic">
                                            Tidak ada data Pendaftar Mahasiswa Online. Klik **Tambah Pendaftar Baru** untuk membuat.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </AdminKampusLayout>
    );
}