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, faSitemap, faExclamationTriangle, faTimes, 
    faImage, faCheckCircle, faToggleOn, faToggleOff, faLink
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';


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

const DeleteConfirmationModal = ({ isOpen, onClose, onConfirm, chart }) => {
    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">
                {/* 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 **"{chart?.title}"**? 
                        {chart?.is_active && (
                            <span className="font-semibold text-red-600 block mt-2">
                                PERINGATAN: Struktur Organisasi ini sedang aktif! Menghapusnya akan membuat halaman publik kampus tidak menampilkan struktur organisasi.
                            </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">
                        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: Struktur Organisasi Index Page ---
// ========================================================================

/**
 * @param {object} props
 * @param {object} props.auth
 * @param {object|null} props.organizationChart - Data tunggal Struktur Organisasi (atau null jika belum ada)
 */
export default function StrukturOrganisasiIndex({ auth, organizationChart }) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    // Kita tidak perlu state chartToDelete lagi karena hanya ada satu item
    const chart = organizationChart; // Data tunggal yang dikirim dari controller

    // Menampilkan modal konfirmasi penghapusan (menggunakan custom modal)
    const handleDeleteClick = () => {
        // Langsung buka modal dengan data chart yang ada
        setIsModalOpen(true);
    };

    const handleConfirmDelete = () => {
        if (chart) {
            // Karena ini singleton, kita tidak perlu ID di route destroy.
            // Gunakan route 'admin.kampus.organisasi.destroy'
            router.delete(route('admin.kampus.organisasi.destroy'), {
                preserveScroll: true,
                onSuccess: () => {
                    setIsModalOpen(false);
                    // setChartToDelete(null); // Tidak perlu lagi
                },
                onError: (errors) => {
                    console.error("Gagal menghapus struktur organisasi:", errors);
                    setIsModalOpen(false);
                    Swal.fire('Gagal!', 'Terjadi kesalahan saat menghapus data.', 'error');
                },
            });
        }
    };

    // LOGIKA INI TIDAK RELEVAN UNTUK SINGLETON DENGAN HANYA 1 DATA
    // const handleUpdateStatus = (chartItem) => { ... };
    // Tombol Aktifkan dan Status (is_active) dihilangkan dari tabel
    // karena di CRUD singleton seperti ini, data yang ada SUDAH OTOMATIS AKTIF
    // (jika Anda ingin mempertahankan is_active, Anda harus menambahkan route updateStatus di controller)
    
    // Logika untuk Tombol Tambah Baru
    const hasChart = !!chart; // true jika ada data, false jika null

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

            {/* Modal Konfirmasi Delete */}
            <DeleteConfirmationModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onConfirm={handleConfirmDelete}
                chart={chart}
            />

            <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={faSitemap} className="mr-3 text-indigo-600" />
                        Daftar Struktur Organisasi Kampus
                    </h3>

                    {/* Header dan Tombol Tambah/Edit */}
                    <div className="flex justify-end mb-6">
                        {hasChart ? (
                            // Tombol Edit/Ganti Data
                            <Link
                                href={route('admin.kampus.organisasi.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 Struktur Organisasi
                            </Link>
                        ) : (
                            // Tombol Tambah Baru
                            <Link
                                href={route('admin.kampus.organisasi.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 Struktur Baru
                            </Link>
                        )}
                    </div>
                    
                    {/* Table Data Struktur Organisasi */}
                    <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">Judul</th>
                                    <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Gambar</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">
                                {hasChart ? (
                                    <tr key={chart.id} className="bg-white">
                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            {chart.title}
                                        </td>
                                        <td className="px-6 py-4 text-center">
                                            {chart.image_url_public ? (
                                                <a href={chart.image_url_public} target="_blank" rel="noopener noreferrer" title="Lihat Gambar" className="inline-block">
                                                    <img
                                                        src={chart.image_url_public} 
                                                        alt={`Struktur ${chart.title}`}
                                                        className="w-20 h-20 object-contain rounded-md mx-auto shadow-md border border-gray-100 transition duration-150 hover:shadow-lg"
                                                        onError={(e) => {
                                                            e.target.onerror = null;
                                                            e.target.src = "https://placehold.co/80x80/E5E7EB/6B7280?text=No+Img";
                                                        }}
                                                    />
                                                </a>
                                            ) : (
                                                <span className="text-gray-400 italic text-xs flex flex-col items-center justify-center h-full">
                                                    <FontAwesomeIcon icon={faImage} className="w-5 h-5 mb-1" />
                                                    Tidak Ada Gambar
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            {new Date(chart.created_at).toLocaleDateString('id-ID', {
                                                year: 'numeric', month: 'short', day: 'numeric'
                                            })}
                                        </td>
                                        <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.organisasi.edit')} // Menggunakan route tanpa ID
                                                    className="transition duration-150 p-2 rounded-full text-blue-600 hover:text-blue-900 hover:bg-blue-100"
                                                    title="Edit Struktur Organisasi"
                                                >
                                                    <FontAwesomeIcon icon={faEdit} className="w-4 h-4" />
                                                </Link>

                                                {/* Tombol Lihat (Opsional) */}
                                                {chart.image_url_public && (
                                                    <a
                                                        href={chart.image_url_public}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                        className="transition duration-150 p-2 rounded-full text-green-600 hover:text-green-900 hover:bg-green-100"
                                                        title="Lihat Gambar Penuh"
                                                    >
                                                        <FontAwesomeIcon icon={faLink} className="w-4 h-4" />
                                                    </a>
                                                )}

                                                {/* Tombol Hapus */}
                                                <button
                                                    onClick={handleDeleteClick} // Memanggil modal untuk data tunggal
                                                    className="transition duration-150 p-2 rounded-full text-red-600 hover:text-red-900 hover:bg-red-100"
                                                    title="Hapus Struktur Organisasi"
                                                >
                                                    <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 struktur organisasi kampus. Klik **Tambah Struktur Baru** untuk membuat.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </AdminKampusLayout>
    );
}