import React, { useState } from 'react';
// Asumsi 'route' global function (dari Ziggy) dan Inertia imports sudah tersedia
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, router } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlusCircle, faEdit, faTrash, faSearch, faBuilding, faToggleOn, faToggleOff, faExclamationTriangle, faTimes } from '@fortawesome/free-solid-svg-icons';
import axios from 'axios';

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

const DeleteConfirmationModal = ({ isOpen, onClose, onConfirm, campus }) => {
    if (!isOpen) return null;

    // Default name jika siakad_campus belum ada
    // Menggunakan ID sebagai fallback terburuk
    const campusName = campus?.siakad_campus?.nama_kampus || campus?.slug || `Kampus ID: ${campus?.id || '?'}`;

    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">
                {/* 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 permanen** data kampus **"{campusName}"**?
                    </p>
                    <p className="mt-2 text-sm text-red-600 font-medium">
                        Aksi ini tidak dapat dibatalkan. Menghapus kampus akan memengaruhi data terkait lainnya.
                    </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 shadow-md"
                    >
                        Ya, Hapus Permanen
                    </button>
                </div>
            </div>
        </div>
    );
};


// Status Badge (dengan logika toggle status menggunakan PUT request via Axios)
const StatusBadge = ({ status, campusId }) => {
    const isActive = status === 'aktif';
    const baseClasses = "px-3 py-1 text-xs font-semibold rounded-full cursor-pointer transition duration-200";
    let colorClasses = "";

    if (isActive) {
        colorClasses = "bg-green-100 text-green-800 hover:bg-green-200";
    } else {
        colorClasses = "bg-red-100 text-red-800 hover:bg-red-200";
    }

    const handleToggle = () => {
        // Memastikan fungsi route() tersedia (dari Ziggy)
        if (typeof route !== 'function') {
            console.error("Fungsi route() (Ziggy) tidak ditemukan.");
            return;
        }

        // Menggunakan Inertia router.put (lebih terintegrasi dengan Inertia daripada Axios di sini)
        router.put(route('admin.super.kampus.toggle-status', campusId), {}, {
            preserveScroll: true,
            onSuccess: () => {
                // Notifikasi sukses (jika ada)
            },
            onError: (errors) => {
                console.error("Gagal mengubah status:", errors);
            }
        });
    };

    return (
        <span className={`${baseClasses} ${colorClasses}`} onClick={handleToggle} title={`Klik untuk mengubah status ke ${isActive ? 'Non-Aktif' : 'Aktif'}`}>
            <FontAwesomeIcon icon={isActive ? faToggleOn : faToggleOff} className="mr-1" />
            {status.toUpperCase()}
        </span>
    );
};

// Pagination component
const Pagination = ({ links }) => {
    if (!links || links.length < 3) return null;
    return (
        <nav className="flex justify-end mt-4 space-x-1">
            {links.map((link, index) => (
                // Pastikan untuk mengabaikan link yang tidak memiliki URL (seperti '...')
                link.url ? (
                    <Link
                        key={index}
                        href={link.url}
                        className={`px-3 py-1 text-xs rounded-lg transition-colors duration-150 ${
                            link.active
                                ? 'bg-indigo-600 text-white font-bold shadow-md'
                                : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                        }`}
                        dangerouslySetInnerHTML={{ __html: link.label }}
                        preserveScroll
                    />
                ) : (
                    <span
                        key={index}
                        className="px-3 py-1 text-xs text-gray-500"
                        dangerouslySetInnerHTML={{ __html: link.label }}
                    />
                )
            ))}
        </nav>
    );
};


// --- Komponen Utama ---

export default function CampusIndex({ auth, campuses }) {
    const [searchTerm, setSearchTerm] = useState('');
    
    // State untuk Modal Hapus
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [campusToDelete, setCampusToDelete] = useState(null);

    const campusData = campuses?.data || [];
    const paginationLinks = campuses?.links || [];

    // Logika Filter di sisi klien (karena data pagination sudah diambil)
    const filteredCampuses = campusData.filter(campus => {
        const name = campus.siakad_campus?.nama_kampus?.toLowerCase() || '';
        const slug = campus.slug?.toLowerCase() || '';
        const city = campus.city?.toLowerCase() || '';
        const term = searchTerm.toLowerCase();

        return name.includes(term) || slug.includes(term) || city.includes(term);
    });

    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
    };

    /**
     * @description Handler untuk menampilkan modal konfirmasi penghapusan.
     * @param {object} campus Data kampus yang akan dihapus.
     */
    const handleDeleteClick = (campus) => {
        setCampusToDelete(campus);
        setIsModalOpen(true);
    };

    /**
     * @description Handler untuk menjalankan penghapusan data setelah dikonfirmasi.
     * Menggunakan Inertia router.delete.
     */
    const handleConfirmDelete = () => {
        if (campusToDelete) {
            // Memastikan fungsi route() tersedia (dari Ziggy)
            if (typeof route !== 'function') {
                console.error("Fungsi route() (Ziggy) tidak ditemukan. Penghapusan dibatalkan.");
                setIsModalOpen(false);
                setCampusToDelete(null);
                return;
            }

            // --- BAGIAN KRITIS UNTUK PENGHAPUSAN DATABASE ---
            router.delete(route('admin.super.kampus.destroy', campusToDelete.id), {
                preserveScroll: true, // Pertahankan posisi scroll setelah refresh
                onSuccess: () => {
                    // Tutup modal dan reset state setelah sukses
                    setIsModalOpen(false);
                    setCampusToDelete(null);
                    // Inertia otomatis akan memuat ulang (reload) halaman dan menampilkan notifikasi (jika diatur di controller)
                },
                onError: (errors) => {
                    console.error("Gagal menghapus kampus:", errors);
                    // Tampilkan notifikasi error ke user jika perlu
                    setIsModalOpen(false); // Tutup modal meskipun error
                    setCampusToDelete(null);
                },
            });
            // --- AKHIR BAGIAN KRITIS ---
        }
    };


    return (
        <AuthenticatedLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Manajemen Data Kampus</h2>}
        >
            <Head title="Data Kampus" />
            
            {/* Modal Konfirmasi Delete */}
            <DeleteConfirmationModal 
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onConfirm={handleConfirmDelete}
                campus={campusToDelete}
            />

            <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-lg p-6">
                    <h3 className="text-2xl font-bold text-gray-800 mb-6 flex items-center">
                        <FontAwesomeIcon icon={faBuilding} className="mr-3 text-indigo-600" />
                        Daftar Kampus Terdaftar
                    </h3>

                    {/* Header dan Filter */}
                    <div className="flex flex-col md:flex-row justify-between items-center mb-6 space-y-4 md:space-y-0">
                        {/* Tombol Tambah Data */}
                        <Link
                            href={typeof route === 'function' ? route('admin.super.kampus.create') : '#'}
                            className="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-lg font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-150 shadow-md w-full md:w-auto justify-center"
                        >
                            <FontAwesomeIcon icon={faPlusCircle} className="w-4 h-4 mr-2" />
                            Tambah Data Kampus Baru
                        </Link>

                        {/* Search Input */}
                        <div className="relative w-full md:w-1/3">
                            <input
                                type="text"
                                value={searchTerm}
                                onChange={handleSearch}
                                placeholder="Cari Nama, Slug, atau Kota..."
                                className="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 pl-10"
                            />
                            <FontAwesomeIcon icon={faSearch} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                        </div>
                    </div>

                    {/* Table Data Kampus */}
                    <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">
                                        Slug
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Nama Kampus (SIAKAD)
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        Kota / Provinsi
                                    </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">
                                        Aksi
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {filteredCampuses.length > 0 ? (
                                    filteredCampuses.map((campus) => (
                                        <tr key={campus.id} className="hover:bg-indigo-50/50 transition duration-150">
                                            {/* Kolom Slug (Kode) */}
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                                {campus.slug}
                                            </td>
                                            {/* Kolom Nama Kampus */}
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 font-semibold">
                                                {campus.siakad_campus?.nama_kampus || 'Nama SIAKAD tidak tersedia'}
                                            </td>
                                            {/* Kolom Kota/Provinsi */}
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                {campus.city} ({campus.province})
                                            </td>
                                            {/* Kolom Status */}
                                            <td className="px-6 py-4 whitespace-nowrap text-center text-sm">
                                                <StatusBadge status={campus.status} campusId={campus.id} />
                                            </td>
                                            {/* Kolom Aksi */}
                                            <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                <div className="flex justify-center space-x-2">
                                                    {/* Edit Button (Link) */}
                                                    <Link 
                                                        href={typeof route === 'function' ? route('admin.super.kampus.edit', campus.id) : `#edit/${campus.id}`}
                                                        className="text-indigo-600 hover:text-indigo-900 transition duration-150 p-2 rounded-full hover:bg-indigo-100"
                                                        title="Edit Data"
                                                    >
                                                        <FontAwesomeIcon icon={faEdit} className="w-4 h-4" />
                                                    </Link>
                                                    
                                                    {/* Delete Button (Trigger Modal) */}
                                                    <button
                                                        onClick={() => handleDeleteClick(campus)}
                                                        className="text-red-600 hover:text-red-900 transition duration-150 p-2 rounded-full hover:bg-red-100"
                                                        title="Hapus Data"
                                                    >
                                                        <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="5" className="px-6 py-4 text-center text-gray-500 italic">
                                            Tidak ada data kampus yang ditemukan.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                    
                    {/* Paginasi */}
                    <Pagination links={paginationLinks} />

                    <div className="mt-4 text-sm text-gray-500">
                        *Data ditampilkan dari relasi `siakad_campus` dan properti utama model `Campus`.
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}