import React from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faArrowLeft, faSave, faCog 
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2'; 

// ========================================================================
// --- Komponen Utama: Sistem Perkuliahan Edit Page ---
// ========================================================================

/**
 * @param {object} props
 * @param {object} props.auth
 * @param {object} props.errors - Errors validasi dari Laravel
 * @param {object} [props.sistemPerkuliahan={}] - Data fitur sistem perkuliahan yang akan diedit. Ditambahkan nilai default {}
 */
// >>> PERUBAHAN UTAMA ADA DI BARIS INI: Menerapkan nilai default {}
export default function SistemPerkuliahanEdit({ auth, errors, sistemPerkuliahan = {} }) {
    
    // Inisialisasi useForm dengan data saat ini
    const { data, setData, put, processing } = useForm({
        // Karena sistemPerkuliahan dijamin ada (walaupun objek kosong), 
        // properti .name, .description, dan .is_active tidak akan menyebabkan error.
        name: sistemPerkuliahan.name || '',
        description: sistemPerkuliahan.description || '',
        // Pastikan nilai boolean is_active memiliki fallback yang tepat, misalnya false.
        is_active: sistemPerkuliahan.is_active === undefined ? false : sistemPerkuliahan.is_active, 
    });

    // --- Form Handlers ---
    const submit = (e) => {
        e.preventDefault();

        // Pencegahan agar tidak mencoba PUT jika sistemPerkuliahan.id tidak ada (misalnya saat terjadi error 404 pada controller)
        if (!sistemPerkuliahan.id) {
            Swal.fire('Error!', 'Data yang akan diperbarui tidak ditemukan.', 'error');
            return;
        }

        Swal.fire({
            title: 'Konfirmasi Perubahan',
            text: "Apakah Anda yakin ingin menyimpan perubahan pada fitur sistem perkuliahan ini?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#2563EB', // blue-600
            cancelButtonColor: '#EF4444',  // red-500
            confirmButtonText: 'Ya, Perbarui',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Gunakan PUT method untuk update
                put(route('admin.kampus.sistem_perkuliahan.update', sistemPerkuliahan.id), {
                    
                    onSuccess: () => {
                        // Tampilkan SweetAlert Toast
                        Swal.fire({
                            toast: true,
                            position: 'top-end', 
                            icon: 'success',
                            title: '✨ Fitur sistem perkuliahan berhasil diperbarui!',
                            showConfirmButton: false,
                            timer: 3000, 
                            timerProgressBar: true,
                            customClass: {
                                container: 'mt-10' 
                            }
                        });
                    },

                    onError: (errors) => {
                        console.error("Gagal memperbarui fitur:", errors);
                        Swal.fire('Gagal!', 'Terjadi kesalahan validasi atau sistem. Silakan periksa kolom form.', 'error');
                    },
                });
            }
        });
    };

    // Tampilkan pesan error 404 (atau error lain) jika ID tidak ada atau data kosong
    if (!sistemPerkuliahan.id) {
        return (
            <AdminKampusLayout user={auth.user} header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Error Data</h2>}>
                <Head title="Data Tidak Ditemukan" />
                <div className="max-w-4xl mx-auto sm:px-6 lg:px-8 py-12">
                    <div className="bg-white overflow-hidden shadow-xl sm:rounded-xl p-8 text-center">
                        <h3 className="text-2xl font-bold text-red-600 mb-4">404 - Data Tidak Ditemukan</h3>
                        <p className="text-gray-600 mb-6">Fitur Sistem Perkuliahan yang Anda cari mungkin tidak ada atau Anda tidak memiliki akses.</p>
                        <Link
                            href={route('admin.kampus.sistem_perkuliahan.index')}
                            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 transition duration-150"
                        >
                            <FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3 mr-2" />
                            Kembali ke Daftar
                        </Link>
                    </div>
                </div>
            </AdminKampusLayout>
        );
    }


    return (
        <AdminKampusLayout
            user={auth.user}
            // Karena sistemPerkuliahan dijamin ada, kita bisa mengakses propertinya.
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Edit Fitur Sistem Perkuliahan: {sistemPerkuliahan.name || 'Memuat...'}</h2>}
        >
            <Head title={`Edit Fitur: ${sistemPerkuliahan.name || 'Memuat...'}`} />

            <div className="max-w-4xl mx-auto sm:px-6 lg:px-8 py-12">
                <div className="bg-white overflow-hidden shadow-xl sm:rounded-xl p-8">

                    {/* Header dan Tombol Kembali */}
                    <div className="flex justify-between items-center mb-6 border-b pb-4">
                        <h3 className="text-xl font-bold text-gray-800 flex items-center">
                            <FontAwesomeIcon icon={faCog} className="mr-3 text-indigo-600" />
                            Formulir Edit Fitur Sistem Perkuliahan
                        </h3>
                        <Link
                            href={route('admin.kampus.sistem_perkuliahan.index')}
                            className="inline-flex items-center px-4 py-2 bg-gray-200 border border-transparent rounded-lg font-semibold text-xs text-gray-700 uppercase tracking-widest hover:bg-gray-300 transition duration-150"
                        >
                            <FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3 mr-2" />
                            Kembali ke Daftar
                        </Link>
                    </div>

                    <form onSubmit={submit} className="space-y-6">
                        
                        {/* 1. Nama Fitur */}
                        <div>
                            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                                Nama Fitur <span className="text-red-500">*</span>
                            </label>
                            <input
                                id="name"
                                type="text"
                                value={data.name}
                                onChange={(e) => setData('name', e.target.value)} 
                                className={`mt-1 block w-full border ${errors.name ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                required
                            />
                            {errors.name && <p className="mt-2 text-sm text-red-600">{errors.name}</p>}
                        </div>

                        {/* 2. Deskripsi Fitur */}
                        <div>
                            <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
                                Deskripsi <span className="text-red-500">*</span>
                            </label>
                            <textarea
                                id="description"
                                value={data.description}
                                onChange={(e) => setData('description', e.target.value)}
                                rows="3"
                                className={`mt-1 block w-full border ${errors.description ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                required
                            />
                            {errors.description && <p className="mt-2 text-sm text-red-600">{errors.description}</p>}
                        </div>

                        {/* 3. Status Aktif */}
                        <div className="flex items-center">
                            <input
                                id="is_active"
                                type="checkbox"
                                checked={data.is_active}
                                onChange={(e) => setData('is_active', e.target.checked)}
                                className="h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
                            />
                            <label htmlFor="is_active" className="ml-2 block text-sm font-medium text-gray-700">
                                Aktif (Tampilkan di halaman publik)
                            </label>
                            {errors.is_active && <p className="mt-2 text-sm text-red-600">{errors.is_active}</p>}
                        </div>
                        
                        {/* Tombol Aksi */}
                        <div className="flex justify-end pt-4 border-t mt-6">
                            <button
                                type="submit"
                                disabled={processing}
                                className={`inline-flex items-center px-6 py-3 border border-transparent rounded-lg font-semibold text-sm uppercase tracking-widest transition ease-in-out duration-150 shadow-md justify-center ${
                                    processing ? 'bg-indigo-400 cursor-not-allowed' : '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={faSave} className="w-4 h-4 mr-2" />
                                {processing ? 'Memperbarui...' : 'Simpan Perubahan'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </AdminKampusLayout>
    );
}