import React, { useEffect, useRef, useMemo } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faArrowLeft, faSave, faImage, faNewspaper, faCalendarDay, faTimes, faPencilAlt
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';

// ========================================================================
// --- Komponen Utama: Berita Edit Page ---
// ========================================================================

/**
 * @param {object} props
 * @param {object} props.auth
 * @param {object} props.errors - Errors validasi dari Laravel
 * @param {object} props.categoryOptions - Pilihan kategori dari controller
 * @param {object} props.newsData - Data berita yang akan diedit
 */
export default function NewsEdit({ auth, errors, categoryOptions = {}, newsData }) {
    
    // Inisialisasi useForm dengan data yang ada dan method PUT
    const { data, setData, post, processing, clearErrors, reset } = useForm({
        // Data yang diambil dari prop newsData
        excerpt: newsData.excerpt || '', 
        content: newsData.content || '', 
        category: newsData.category || '', 
        published_at: newsData.published_at || '', 
        
        // Form field untuk file baru
        image_file: null, 
        
        // Flag untuk menandakan penghapusan gambar yang sudah ada (jika tidak ada file baru)
        _delete_image: false, 

        // Method Spoofer untuk Inertia/Laravel PUT/PATCH request
        _method: 'put', 
    });

    const imageRef = useRef(null);

    // --- Image Preview Logic ---

    // Menentukan URL pratinjau gambar yang akan ditampilkan di UI
    // 1. Prioritas: File baru yang diunggah (image_file)
    // 2. Fallback: Gambar yang sudah ada (newsData.image_url) jika tidak ditandai untuk dihapus
    const previewUrl = useMemo(() => {
        // Jika ada file baru, buat Object URL
        if (data.image_file) {
            return URL.createObjectURL(data.image_file);
        }
        
        // Jika tidak ada file baru DAN ditandai untuk dihapus, kembalikan null
        if (data._delete_image) {
            return null;
        }

        // Jika tidak ada file baru dan tidak ditandai untuk dihapus, gunakan URL gambar lama
        return newsData.image_url;

    }, [data.image_file, data._delete_image, newsData.image_url]);


    // Menghapus file gambar dari state dan input file
    const clearImage = () => {
        // Hapus file dari input
        if (imageRef.current) {
            imageRef.current.value = null;
        }

        // Set state data form:
        setData(oldData => ({
            ...oldData,
            image_file: null, // Hapus file baru (jika ada)
            // Tandai untuk hapus, hanya jika ada image_url yang lama
            _delete_image: newsData.image_url ? true : false, 
        }));
        
        clearErrors('image_file');
    };

    // Cleanup URL Pratinjau saat komponen dilepas/state berubah
    useEffect(() => {
        return () => {
            // Cabut Object URL untuk file baru (jika ada)
            if (data.image_file && previewUrl && previewUrl.startsWith('blob:')) {
                URL.revokeObjectURL(previewUrl);
            }
        };
    }, [data.image_file, previewUrl]);

    // --- Form Handlers ---

    const submit = (e) => {
        e.preventDefault();

        Swal.fire({
            title: 'Konfirmasi Perubahan Berita',
            text: "Apakah Anda yakin dengan perubahan ini dan ingin menyimpannya?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10B981', 
            cancelButtonColor: '#EF4444', 
            confirmButtonText: 'Ya, Update',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Gunakan POST dengan method spoofing PUT untuk update
                post(route('admin.kampus.berita.update', newsData.id), { 
                    onSuccess: () => {
                        // Tidak perlu reset semua, hanya reset file input
                        setData('image_file', null);
                        setData('_delete_image', false); // Reset flag
                        if (imageRef.current) {
                            imageRef.current.value = null;
                        }
                        Swal.fire('Berhasil!', 'Berita telah berhasil diperbarui.', 'success');
                    },
                    onError: (errors) => {
                        console.error("Gagal memperbarui berita:", errors);
                        Swal.fire('Gagal!', 'Terjadi kesalahan saat menyimpan data. Periksa kembali input Anda.', 'error');
                    },
                    // PENTING: forceFormData harus true karena kita mengirim file (image_file)
                    forceFormData: true, 
                });
            }
        });
    };
    
    // Cek apakah categoryOptions kosong
    const isCategoryEmpty = Object.keys(categoryOptions).length === 0;

    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Edit Berita: {newsData.excerpt}</h2>}
        >
            <Head title={`Edit Berita: ${newsData.excerpt}`} />

            <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">

                    {/* --- DEBUGGING SECTION (Dibiarkan untuk referensi) --- */}
                    {isCategoryEmpty && (
                        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                            <strong className="font-bold flex items-center">
                                <FontAwesomeIcon icon={faBug} className="mr-2" /> DEBUG ALERT:
                            </strong>
                            <span className="block sm:inline"> Kategori kosong. Pastikan Controller (NewsController) mengirim data.</span>
                        </div>
                    )}
                    {/* --- END DEBUGGING SECTION --- */}
                    
                    <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={faPencilAlt} className="mr-3 text-emerald-600" />
                            Formulir Edit Berita
                        </h3>
                        <Link
                            href={route('admin.kampus.berita.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. Judul/Ringkasan Berita (Excerpt) */}
                        <div>
                            <label htmlFor="excerpt" className="block text-sm font-medium text-gray-700 mb-1">
                                Judul / Ringkasan (Max 500 Karakter) <span className="text-red-500">*</span>
                            </label>
                            <input
                                id="excerpt"
                                type="text"
                                value={data.excerpt}
                                onChange={(e) => setData('excerpt', e.target.value)} 
                                className={`mt-1 block w-full border ${errors.excerpt ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                                required
                            />
                            {errors.excerpt && <p className="mt-2 text-sm text-red-600">{errors.excerpt}</p>}
                        </div>
                        
                        {/* Grup 2 Kolom: Kategori & Tanggal Publikasi */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {/* 2. Kategori */}
                            <div>
                                <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-1">
                                    Kategori <span className="text-red-500">*</span>
                                </label>
                                <select
                                    id="category"
                                    value={data.category}
                                    onChange={(e) => setData('category', e.target.value)}
                                    className={`mt-1 block w-full border ${errors.category ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                                    required
                                >
                                    {/* Opsi Placeholder */}
                                    <option value="" disabled>--- Pilih Kategori ---</option>

                                    {/* Iterasi Pilihan Kategori */}
                                    {Object.entries(categoryOptions).map(([key, value]) => (
                                        <option key={key} value={key}>{value}</option>
                                    ))}
                                </select>
                                {errors.category && <p className="mt-2 text-sm text-red-600">{errors.category}</p>}
                            </div>

                            {/* 3. Tanggal Publikasi (Published At) */}
                            <div>
                                <label htmlFor="published_at" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                    <FontAwesomeIcon icon={faCalendarDay} className="w-4 h-4 mr-2" />
                                    Tanggal Publikasi (Kosongkan untuk Draft)
                                </label>
                                <input
                                    id="published_at"
                                    type="date"
                                    value={data.published_at || ''}
                                    onChange={(e) => setData('published_at', e.target.value)}
                                    className={`mt-1 block w-full border ${errors.published_at ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                                />
                                {errors.published_at && <p className="mt-2 text-sm text-red-600">{errors.published_at}</p>}
                            </div>

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

                        {/* ======================================================= */}
                        {/* 5. UNGGAH GAMBAR UTAMA (image_file) */}
                        {/* ======================================================= */}
                        <div>
                            <label htmlFor="image_file" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                <FontAwesomeIcon icon={faImage} className="w-4 h-4 mr-2" />
                                Gambar Utama Berita (Max 2MB)
                                {/* Hanya wajib jika tidak ada gambar lama dan tidak ada gambar baru yang diunggah */}
                                {(!newsData.image_url && !data.image_file) && <span className="text-red-500 ml-1">*</span>} 
                            </label>
                            
                            {/* Input File - Ganti gambar lama atau upload baru */}
                            <input
                                id="image_file"
                                type="file"
                                ref={imageRef}
                                // Jika user upload file baru, reset flag _delete_image
                                onChange={(e) => setData(oldData => ({ ...oldData, image_file: e.target.files[0], _delete_image: false }))}
                                className={`mt-1 block w-full text-sm text-gray-500
                                    file:mr-4 file:py-2 file:px-4
                                    file:rounded-lg file:border-0
                                    file:text-sm file:font-semibold
                                    file:bg-emerald-50 file:text-emerald-700
                                    hover:file:bg-emerald-100
                                    border ${errors.image_file ? 'border-red-500' : 'border-gray-300'} rounded-lg
                                `}
                                accept="image/*"
                            />
                            {errors.image_file && <p className="mt-2 text-sm text-red-600">{errors.image_file}</p>}

                            {/* Pratinjau Gambar (Menggunakan previewUrl yang sudah dihitung) */}
                            {previewUrl && (
                                <div className="mt-4 relative w-full max-w-sm">
                                    <img 
                                        src={previewUrl} 
                                        alt="Pratinjau Gambar Berita" 
                                        className="w-full h-auto object-cover rounded-lg shadow-lg border border-gray-200" 
                                    />
                                    {/* Tombol Hapus Gambar */}
                                    <button
                                        type="button"
                                        onClick={clearImage}
                                        className="absolute top-2 right-2 p-1 bg-red-600 text-white rounded-full shadow-lg hover:bg-red-700 transition"
                                        title="Hapus Gambar"
                                    >
                                        <FontAwesomeIcon icon={faTimes} className="w-4 h-4" />
                                    </button>
                                </div>
                            )}

                            {/* Pesan status jika gambar lama ditandai untuk dihapus */}
                            {data._delete_image && newsData.image_url && !data.image_file && (
                                <p className="mt-2 text-sm text-red-600">
                                    Gambar utama akan **dihapus** saat disimpan. Upload file baru untuk mengganti.
                                </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-emerald-400 cursor-not-allowed' : 'bg-emerald-600 text-white hover:bg-emerald-700 active:bg-emerald-900 focus:outline-none focus:border-emerald-900 focus:ring ring-emerald-300'
                                }`}
                            >
                                <FontAwesomeIcon icon={faSave} className="w-4 h-4 mr-2" />
                                {processing ? 'Memperbarui...' : 'Update Berita'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </AdminKampusLayout>
    );
}
