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

// Modal for delete confirmation
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">
                <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 Kurikulum
                    </h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
                        <FontAwesomeIcon icon={faTimes} className="w-5 h-5" />
                    </button>
                </div>

                <div className="p-6">
                    <p className="text-gray-700">
                        Anda yakin ingin menghapus kurikulum **"{item.semester}"** untuk jurusan **"{item.jurusan.name}"**? 
                        Data yang dihapus tidak dapat dikembalikan.
                    </p>
                </div>

                <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>
    );
};

// Main Kurikulum Index Page
export default function KurikulumIndex({ auth, curriculums = [] }) {
    const { flash } = usePage().props;
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [itemToDelete, setItemToDelete] = useState(null);
    
    // Check if data exists and is an array
    const items = Array.isArray(curriculums.data) ? curriculums.data : [];

    // Handle flash messages
    useEffect(() => {
        if (flash && flash.success) {
            Swal.fire('Berhasil!', flash.success, 'success');
        } else if (flash && flash.error) {
            Swal.fire('Gagal!', flash.error, 'error');
        }
    }, [flash]);

    // Delete handler
    const handleDeleteClick = (item) => { 
        setItemToDelete(item); 
        setIsModalOpen(true);
    };

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

    // Ensure courses is an array before using map
    const formatCourses = (courses) => {
        if (!Array.isArray(courses)) return 'No courses available'; // Fallback if not an array
        return courses.map((course, index) => `${course.name} (${course.sks} SKS)`).join(', ');
    };

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

            <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={faFlagCheckered} className="mr-3 text-red-600" />
                        Daftar Kurikulum
                    </h3>

                    <div className="flex justify-between items-center mb-6">
                        <div className="text-gray-500 italic text-sm">Total: {items.length} Kurikulum</div>
                        <Link href={route('admin.kampus.kurikulum.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 Kurikulum Baru
                        </Link>
                    </div>

                    <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">Jurusan</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Semester</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Mata Kuliah</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">
                                {items.length > 0 ? (
                                    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.jurusan ? item.jurusan.name : 'N/A'}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-center">{item.semester}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-center">{formatCourses(item.courses)}</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.kurikulum.edit', item.id)}
                                                        className="transition duration-150 p-2 rounded-full text-blue-600 hover:text-blue-900 hover:bg-blue-100"
                                                        title="Edit Kurikulum"
                                                    >
                                                        <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"
                                                        title="Hapus Kurikulum"
                                                    >
                                                        <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 kurikulum. Klik **Tambah Kurikulum Baru** untuk membuat.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </AdminKampusLayout>
    );
}
