import React, { useState } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, router } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faPlusCircle, faEdit, faTrash, faExclamationTriangle, faTimes, 
    faImage, faCheckCircle, faToggleOn, faToggleOff, faLink, faFileImage,
    faCaretRight
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';


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

/**
 * Modal Konfirmasi Hapus untuk Brosur Kampus
 */
const DeleteConfirmationModal = ({ isOpen, onClose, onConfirm }) => {
    if (!isOpen) 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-transform duration-300 scale-95 hover: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 data brosur** ini? 
                        <span className="font-semibold text-red-600 block mt-2">
                            PERINGATAN: Semua gambar brosur yang terkait juga akan dihapus permanen.
                        </span>
                    </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 shadow-sm">
                        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
                    </button>
                </div>
            </div>
        </div>
    );
};

// ========================================================================
// --- Komponen Utama: Brosur Kampus Index Page ---
// ========================================================================

/**
 * Halaman Indeks untuk Manajemen Brosur Kampus (Singleton CRUD)
 * @param {object} props
 * @param {object} props.auth
 * @param {object|null} props.brosurData - Data Brosur tunggal (atau null jika belum ada)
 */
export default function BrosurKampusIndex({ auth, brosurData }) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    
    // Logika untuk Tombol Tambah/Edit
    const hasBrochure = !!brosurData; // true jika ada data, false jika null

    // Menampilkan modal konfirmasi penghapusan
    const handleDeleteClick = () => {
        setIsModalOpen(true);
    };

    const handleConfirmDelete = () => {
        if (brosurData) {
            router.delete(route('admin.kampus.brosur.destroy'), {
                preserveScroll: true,
                onSuccess: () => {
                    setIsModalOpen(false);
                    Swal.fire('Berhasil!', 'Brosur berhasil dihapus.', 'success');
                },
                onError: (errors) => {
                    console.error("Gagal menghapus brosur:", errors);
                    setIsModalOpen(false);
                    Swal.fire('Gagal!', 'Terjadi kesalahan saat menghapus data brosur.', 'error');
                },
            });
        }
    };
    
    // Fungsi untuk mengubah status is_active
    const toggleIsActive = () => {
        if (!brosurData) return;

        // Kirim permintaan PUT/PATCH untuk mengubah status
        router.patch(route('admin.kampus.brosur.update'), {
            is_active: !brosurData.is_active,
            // Perlu mengirimkan field lain jika required, tapi karena controller sudah direvisi, 
            // kita hanya perlu memastikan data yang tidak required diabaikan/diisi default
            // Kita bisa mengirimkan title (jika ada di DB) agar validasi lewat, atau pastikan
            // field 'title' sudah benar-benar dihapus dari DB dan model (seperti yang Anda minta).
            // Karena title sudah dihapus dari controller/model, kita TIDAK PERLU mengirimkannya.
        }, {
            preserveScroll: true,
            onSuccess: () => {
                Swal.fire('Status Diubah!', `Brosur berhasil di${!brosurData.is_active ? 'aktifkan' : 'nonaktifkan'}.`, 'success');
            },
            onError: (errors) => {
                console.error("Gagal mengubah status:", errors);
                Swal.fire('Gagal!', 'Terjadi kesalahan saat mengubah status keaktifan.', 'error');
            }
        });
    };


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

            {/* Modal Konfirmasi Delete */}
            <DeleteConfirmationModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onConfirm={handleConfirmDelete}
                // Hapus prop 'brochure' karena 'title' tidak lagi digunakan di modal
            />

            <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={faFileImage} className="mr-3 text-red-600" />
                        Data Brosur Kampus
                    </h3>

                    {/* Header dan Tombol Tambah/Edit */}
                    <div className="flex justify-between items-center mb-6">
                        <p className="text-gray-600 text-sm">
                            Kelola gambar brosur (Depan dan Belakang) yang akan ditampilkan di halaman publik kampus Anda.
                        </p>
                        {hasBrochure ? (
                            // Tombol Edit/Ganti Data
                            <Link
                                href={route('admin.kampus.brosur.edit')} 
                                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-blue-600 text-white hover:bg-blue-700 active:bg-blue-900 focus:outline-none focus:border-blue-900 focus:ring ring-blue-300"
                            >
                                <FontAwesomeIcon icon={faEdit} className="w-4 h-4 mr-2" />
                                Edit Brosur
                            </Link>
                        ) : (
                            // Tombol Tambah Baru
                            <Link
                                href={route('admin.kampus.brosur.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" />
                                Unggah Brosur Baru
                            </Link>
                        )}
                    </div>
                    
                    {/* Tabel Data Brosur 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>
                                    {/* Kolom Title diganti menjadi Status */}
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status & Waktu Unggah</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Gambar Depan</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Gambar Belakang</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">
                                {hasBrochure ? (
                                    <tr key={brosurData.id} className="bg-white hover:bg-gray-50 transition duration-150">
                                        
                                        {/* Kolom Status & Waktu Unggah */}
                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            <div className="flex flex-col space-y-2">
                                                {/* Status Keaktifan */}
                                                <button
                                                    onClick={toggleIsActive}
                                                    className={`flex items-center text-xs font-bold rounded-full px-3 py-1.5 transition ${
                                                        brosurData.is_active 
                                                            ? 'bg-green-100 text-green-700 hover:bg-green-200' 
                                                            : 'bg-red-100 text-red-700 hover:bg-red-200'
                                                    }`}
                                                >
                                                    <FontAwesomeIcon 
                                                        icon={brosurData.is_active ? faToggleOn : faToggleOff} 
                                                        className={`w-4 h-4 mr-2 ${brosurData.is_active ? 'text-green-500' : 'text-red-500'}`} 
                                                    />
                                                    {brosurData.is_active ? 'Aktif' : 'Nonaktif'}
                                                </button>
                                                
                                                {/* Waktu Unggah */}
                                                <span className="text-gray-500 text-xs mt-1">
                                                    Unggah: {new Date(brosurData.created_at).toLocaleDateString('id-ID', {
                                                        year: 'numeric', month: 'short', day: 'numeric'
                                                    })}
                                                </span>
                                            </div>
                                        </td>

                                        {/* Gambar Depan */}
                                        <td className="px-6 py-4 text-left text-sm text-gray-500">
                                            {brosurData.image_front_url_public ? (
                                                <a href={brosurData.image_front_url_public} target="_blank" rel="noopener noreferrer" title="Lihat Gambar Depan" className="inline-flex items-center text-blue-600 hover:text-blue-800 transition">
                                                    <FontAwesomeIcon icon={faLink} className="w-4 h-4 mr-1" />
                                                    Lihat Gambar
                                                </a>
                                            ) : (
                                                <span className="text-gray-400 italic text-xs flex items-center">
                                                    <FontAwesomeIcon icon={faImage} className="w-4 h-4 mr-1" />
                                                    Tidak Ada Gambar
                                                </span>
                                            )}
                                        </td>

                                        {/* Gambar Belakang */}
                                        <td className="px-6 py-4 text-left text-sm text-gray-500">
                                            {brosurData.image_back_url_public ? (
                                                <a href={brosurData.image_back_url_public} target="_blank" rel="noopener noreferrer" title="Lihat Gambar Belakang" className="inline-flex items-center text-blue-600 hover:text-blue-800 transition">
                                                    <FontAwesomeIcon icon={faLink} className="w-4 h-4 mr-1" />
                                                    Lihat Gambar
                                                </a>
                                            ) : (
                                                <span className="text-gray-400 italic text-xs flex items-center">
                                                    <FontAwesomeIcon icon={faImage} className="w-4 h-4 mr-1" />
                                                    Tidak Ada Gambar
                                                </span>
                                            )}
                                        </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
                                                    href={route('admin.kampus.brosur.edit')}
                                                    className="transition duration-150 p-2 rounded-full text-blue-600 hover:text-blue-900 hover:bg-blue-100"
                                                    title="Edit Brosur Kampus"
                                                >
                                                    <FontAwesomeIcon icon={faEdit} className="w-4 h-4" />
                                                </Link>

                                                {/* Tombol Hapus */}
                                                <button
                                                    onClick={handleDeleteClick} 
                                                    className="transition duration-150 p-2 rounded-full text-red-600 hover:text-red-900 hover:bg-red-100"
                                                    title="Hapus Brosur Kampus"
                                                >
                                                    <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ) : (
                                    <tr>
                                        <td colSpan="4" className="px-6 py-8 text-center text-gray-500 italic">
                                            Tidak ada data brosur kampus. Klik **Unggah Brosur Baru** untuk membuat.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                    
                    {/* Catatan Kaki */}
                    <div className="mt-8 p-4 bg-yellow-50 border-l-4 border-yellow-400 text-yellow-800 rounded">
                        <p className="font-semibold flex items-center">
                            <FontAwesomeIcon icon={faExclamationTriangle} className="mr-2 w-4 h-4" />
                            Catatan Penting
                        </p>
                        <ul className="list-disc list-inside mt-2 ml-4 text-sm">
                            <li>Setiap kampus hanya boleh memiliki **satu** data brosur.</li>
                            <li>Klik tombol **Aktif/Nonaktif** untuk mengontrol tampilan brosur di halaman publik.</li>
                        </ul>
                    </div>
                </div>
            </div>
        </AdminKampusLayout>
    );
}