import React, { useState } from 'react';
// Asumsi path layout dan Inertia/React hooks sudah benar
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, router } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faPlusCircle, faEdit, faTrash, faExclamationTriangle, faTimes, 
    faCheckCircle, faToggleOn, faToggleOff, faLink, faCog,
    // Menggunakan faCog atau faCheckCircle untuk Sistem Perkuliahan
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';


// ========================================================================
// --- Komponen Bantuan: Modal Konfirmasi Hapus Kustom ---
// ========================================================================

/**
 * Modal Konfirmasi Penghapusan untuk data Sistem Perkuliahan
 * @param {object} props
 * @param {boolean} props.isOpen
 * @param {function} props.onClose
 * @param {function} props.onConfirm
 * @param {object|null} props.item - Data Sistem Perkuliahan yang akan dihapus
 */
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
                    </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 fitur **"{item.name}"**? 
                        {item.is_active && (
                            <span className="font-semibold text-red-600 block mt-2">
                                PERINGATAN: Fitur ini sedang aktif! Hapus hanya jika yakin tidak diperlukan lagi.
                            </span>
                        )}
                        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: Sistem Perkuliahan Index Page ---
// ========================================================================

/**
 * @param {object} props
 * @param {object} props.auth
 * @param {array} props.items - Daftar Fitur Sistem Perkuliahan Kampus
 */
export default function SistemPerkuliahanIndex({ auth, items }) {
    // Mengganti 'facilities' menjadi 'items'
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [itemToDelete, setItemToDelete] = useState(null); // Mengganti 'facilityToDelete'

    // --- CRUD Handlers ---

    // 1. Tampilkan Modal Konfirmasi Penghapusan
    const handleDeleteClick = (item) => { // Mengganti 'facility'
        setItemToDelete(item); // Mengganti 'setFacilityToDelete'
        setIsModalOpen(true);
    };

    // 2. Konfirmasi dan Eksekusi Penghapusan
    const handleConfirmDelete = () => {
        if (itemToDelete) {
            // Mengganti rute fasilitas menjadi sistem_perkuliahan
            router.delete(route('admin.kampus.sistem_perkuliahan.destroy', itemToDelete.id), {
                preserveScroll: true,
                onSuccess: () => {
                    setIsModalOpen(false);
                    setItemToDelete(null);
                    Swal.fire('Berhasil!', 'Fitur sistem perkuliahan telah dihapus.', 'success');
                },
                onError: (errors) => {
                    console.error("Gagal menghapus fitur:", errors);
                    setIsModalOpen(false);
                    Swal.fire('Gagal!', 'Terjadi kesalahan saat menghapus data.', 'error');
                },
            });
        }
    };

    // 3. Toggle Status Aktif/Nonaktif
    const handleUpdateStatus = (item) => { // Mengganti 'facility'
        const newStatus = !item.is_active;
        const confirmText = newStatus ? 
            `Anda yakin ingin MENGAKTIFKAN fitur "${item.name}"?` : // Mengganti 'facility.title' ke 'item.name'
            `Anda yakin ingin MENONAKTIFKAN fitur "${item.name}"?`; // Mengganti 'facility.title' ke 'item.name'
        
        Swal.fire({
            title: 'Ubah Status',
            text: confirmText,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#10B981', // green-500
            cancelButtonColor: '#EF4444',  // red-500
            confirmButtonText: newStatus ? 'Ya, Aktifkan' : 'Ya, Nonaktifkan'
        }).then((result) => {
            if (result.isConfirmed) {
                // Mengganti rute fasilitas menjadi sistem_perkuliahan
                router.patch(route('admin.kampus.sistem_perkuliahan.update.status', item.id), {
                    is_active: newStatus
                }, {
                    preserveScroll: true,
                    onSuccess: () => {
                        Swal.fire('Berhasil!', `Status fitur "${item.name}" telah diubah.`, 'success'); // Mengganti 'facility.title' ke 'item.name'
                    },
                    onError: (errors) => {
                        console.error("Gagal mengubah status:", errors);
                        Swal.fire('Gagal!', 'Terjadi kesalahan saat mengubah status.', 'error');
                    },
                });
            }
        });
    };

    const hasItems = items && items.length > 0; // Mengganti 'hasFacilities'

    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Manajemen Fitur Sistem Perkuliahan</h2>}
        >
            <Head title="Fitur Sistem Perkuliahan Kampus" />

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

            <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">
                        {/* Mengganti ikon */}
                        <FontAwesomeIcon icon={faCog} className="mr-3 text-indigo-600" />
                        Daftar Fitur Sistem Perkuliahan
                    </h3>

                    {/* Header dan Tombol Tambah Baru */}
                    <div className="flex justify-end mb-6">
                        <Link
                            // Mengganti rute fasilitas menjadi sistem_perkuliahan
                            href={route('admin.kampus.sistem_perkuliahan.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-indigo-600 text-white hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300"
                        >
                            <FontAwesomeIcon icon={faPlusCircle} className="w-4 h-4 mr-2" />
                            Tambah Fitur Baru
                        </Link>
                    </div>
                    
                    {/* Table Data Sistem Perkuliahan */}
                    <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/3">Nama Fitur</th>
                                    {/* Kolom Gambar (Image) dihapus */}
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/3">Deskripsi Singkat</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Dibuat</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {hasItems ? (
                                    items.map((item) => ( // Mengganti 'facility'
                                        <tr key={item.id} className="hover:bg-gray-50 transition duration-100">
                                            <td className="px-6 py-4 whitespace-normal text-sm font-semibold text-gray-900">
                                                {item.name} {/* Mengganti 'facility.title' ke 'item.name' */}
                                            </td>
                                            
                                            {/* Deskripsi */}
                                            <td className="px-6 py-4 whitespace-normal text-sm text-gray-500">
                                                <p className="text-xs text-gray-500 font-normal line-clamp-3">{item.description}</p>
                                            </td>

                                            {/* Status */}
                                            <td className="px-6 py-4 whitespace-nowrap text-center">
                                                <button
                                                    onClick={() => handleUpdateStatus(item)}
                                                    className={`transition duration-150 p-2 rounded-full ${item.is_active 
                                                        ? 'text-green-600 hover:text-green-800 hover:bg-green-100' 
                                                        : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'
                                                    }`}
                                                    title={item.is_active ? 'Nonaktifkan Fitur' : 'Aktifkan Fitur'}
                                                >
                                                    <FontAwesomeIcon 
                                                        icon={item.is_active ? faToggleOn : faToggleOff} 
                                                        className="w-6 h-6"
                                                    />
                                                </button>
                                                <span className={`block text-xs font-medium ${item.is_active ? 'text-green-600' : 'text-gray-500'}`}>
                                                    {item.is_active ? 'Aktif' : 'Nonaktif'}
                                                </span>
                                            </td>
                                            
                                            {/* Dibuat */}
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center">
                                                {new Date(item.created_at).toLocaleDateString('id-ID', {
                                                    year: 'numeric', month: 'short', day: 'numeric'
                                                })}
                                            </td>

                                            {/* Aksi */}
                                            <td className="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                                                <div className="flex justify-center space-x-2">
                                                    
                                                    {/* Tombol Edit */}
                                                    <Link
                                                        // Mengganti rute fasilitas menjadi sistem_perkuliahan
                                                        href={route('admin.kampus.sistem_perkuliahan.edit', item.id)}
                                                        className="transition duration-150 p-2 rounded-full text-blue-600 hover:text-blue-900 hover:bg-blue-100"
                                                        title="Edit Fitur"
                                                    >
                                                        <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 Fitur"
                                                    >
                                                        <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="5" className="px-6 py-8 text-center text-gray-500 italic">
                                            Tidak ada data fitur sistem perkuliahan kampus. Klik **Tambah Fitur Baru** untuk membuat.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </AdminKampusLayout>
    );
}