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, faTimeline, faTimes, faToggleOn, faToggleOff } 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">
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-md">
                {/* Header */}
                <div className="p-6 border-b 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 Timeline
                    </h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
                        <FontAwesomeIcon icon={faTimes} className="w-5 h-5" />
                    </button>
                </div>

                {/* Body */}
                <div className="p-6">
                    <p className="text-gray-700">
                        Anda yakin ingin menghapus timeline pendaftaran **"{item.academic_year}"**? 
                        {item.active && <span className="font-semibold text-red-600 block mt-2">PERINGATAN: Timeline ini sedang aktif!</span>}
                        Data yang dihapus tidak dapat dikembalikan.
                    </p>
                </div>

                {/* Footer */}
                <div className="p-6 border-t 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">
                        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">
                        Ya, Hapus
                    </button>
                </div>
            </div>
        </div>
    );
};

// ========================================================================
// --- Komponen Utama: Timeline Pendaftaran Index Page ---
// ========================================================================

export default function TimelinePendaftaranIndex({ auth, timelineItems = [] }) {
    const { items: rawItems, academicYears } = usePage().props;
    const [selectedYear, setSelectedYear] = useState('');
    const [filteredItems, setFilteredItems] = useState(rawItems);
    const items = Array.isArray(filteredItems) ? filteredItems : Array.isArray(timelineItems) ? timelineItems : [];
    const { flash } = usePage().props;

    // Filter items by academic year
    const handleYearFilterChange = (e) => {
        const year = e.target.value;
        setSelectedYear(year);
        setFilteredItems(year ? rawItems.filter(item => item.academic_year === year) : rawItems);
    };

    // 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.timeline.destroy', itemToDelete.id), {
                preserveScroll: true,
                onSuccess: () => {
                    setIsModalOpen(false);
                    setItemToDelete(null);
                },
                onError: () => {
                    Swal.fire('Gagal!', 'Terjadi kesalahan saat menghapus data.', 'error');
                    setIsModalOpen(false);
                },
            });
        }
    };

    // 3. Toggle Status Aktif/Non-Aktif
    const handleUpdateStatus = (item) => {
        const newStatus = item.active === 1 ? 0 : 1; // Toggle status

        // Konfirmasi perubahan status
        const confirmText = newStatus === 1 ? 
            `Anda yakin ingin MENGAKTIFKAN timeline "${item.academic_year}"?` : 
            `Anda yakin ingin MENONAKTIFKAN timeline "${item.academic_year}"?`;

        Swal.fire({
            title: 'Ubah Status Timeline',
            text: confirmText,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: newStatus === 1 ? '#10B981' : '#F59E0B',
            cancelButtonColor: '#EF4444',
            confirmButtonText: newStatus === 1 ? 'Ya, Aktifkan' : 'Ya, Non-Aktifkan'
        }).then((result) => {
            if (result.isConfirmed) {
                router.post(route('admin.kampus.timeline.toggleActive', item.id), {
                    active: newStatus
                }, {
                    preserveScroll: true,
                    onSuccess: () => Swal.fire('Berhasil!', 'Status timeline berhasil diperbarui.', 'success'),
                    onError: () => Swal.fire('Gagal!', 'Terjadi kesalahan saat mengubah status.', 'error'),
                });
            }
        });
    };

    const hasItems = items.length > 0;

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

            {/* 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={faTimeline} className="mr-3 text-red-600" />
                        Daftar Timeline Pendaftaran
                    </h3>

                    {/* Filter Tahun Ajaran */}
                    <div className="mb-4">
                        <select className="p-2 border rounded-md" value={selectedYear} onChange={handleYearFilterChange}>
                            <option value="">-- Pilih Tahun Ajaran --</option>
                            {academicYears && academicYears.length > 0 && academicYears.map((year) => (
                                <option key={year} value={year}>{year}</option>
                            ))}
                        </select>
                    </div>

                    {/* Header dan Tombol Tambah Baru */}
                    <div className="flex justify-between items-center mb-6">
                        <div className="text-gray-500 italic text-sm">Total: {items.length} Timeline</div>
                        <Link href={route('admin.kampus.timeline.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">
                            <FontAwesomeIcon icon={faPlusCircle} className="w-4 h-4 mr-2" />
                            Tambah Timeline Pendaftaran Baru
                        </Link>
                    </div>

                    {/* Table Data Timeline Pendaftaran */}
                    <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-3/12">Tahun Ajaran</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-3/12">Gelombang</th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-3/12">Event</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-1/12">Aksi</th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {hasItems ? (
                                    items.map((item) => (
                                        <tr key={item.id} className="hover:bg-gray-50 transition duration-100">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{item.academic_year}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                {item.waves ? item.waves.map(wave => `${wave.name} (${new Date(wave.start_date).toLocaleDateString()} - ${new Date(wave.end_date).toLocaleDateString()})`).join(', ') : 'N/A'}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                {item.events ? item.events.map(event => `${event.name} (${new Date(event.date).toLocaleDateString()})`).join(', ') : 'N/A'}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-center">
                                                <button
                                                    onClick={() => handleUpdateStatus(item)}
                                                    className={`transition duration-150 p-2 rounded-full ${item.active === 1 ? 'text-green-600 hover:text-green-800 hover:bg-green-100' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'}`}
                                                    title={item.active === 1 ? 'Non-Aktifkan Timeline' : 'Aktifkan Timeline'}
                                                >
                                                    <FontAwesomeIcon icon={item.active === 1 ? faToggleOn : faToggleOff} className="w-6 h-6" />
                                                </button>
                                                <span className={`block text-xs font-medium ${item.active === 1 ? 'text-green-600' : 'text-yellow-600'}`}>
                                                    {item.active === 1 ? 'Aktif' : 'Non-Aktif'}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                                                <div className="flex justify-center space-x-2">
                                                    <Link
                                                        href={route('admin.kampus.timeline.edit', item.id)}
                                                        className="transition duration-150 p-2 rounded-full text-blue-600 hover:text-blue-900 hover:bg-blue-100"
                                                        title="Edit Timeline"
                                                    >
                                                        <FontAwesomeIcon icon={faEdit} className="w-4 h-4" />
                                                    </Link>

                                                    <button
                                                        onClick={() => handleDeleteClick(item)} 
                                                        className={`transition duration-150 p-2 rounded-full text-red-600 hover:text-red-900 hover:bg-red-100 ${item.active === 1 ? 'opacity-50 cursor-not-allowed' : ''}`}
                                                        title="Hapus Timeline"
                                                        disabled={item.active === 1}  // Disable the delete button if status is active
                                                    >
                                                        <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 timeline pendaftaran. Klik **Tambah Timeline Pendaftaran Baru** untuk membuat.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </AdminKampusLayout>
    );
}
