import React, { useEffect, useRef, useState } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faArrowLeft, faSave, faCamera, faImages, faTimes, faTag, faTrash
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';

// ========================================================================
// --- Komponen Utama: Gallery Edit Page (Tema Biru, Input Sesuai Controller) ---
// ========================================================================

/**
 * Komponen untuk mengedit item galeri (foto) yang sudah ada.
 * @param {object} props
 * @param {object} props.auth
 * @param {object} props.errors - Errors validasi dari Laravel
 * @param {object} props.categoryOptions - Opsi kategori dari Controller
 * @param {object} props.itemData - Data galeri yang akan diedit
 */
export default function GalleryEdit({ auth, errors, categoryOptions, itemData }) {
    
    // Inisialisasi useForm disesuaikan dengan controller:
    const { data, setData, post, processing, clearErrors } = useForm({
        // Data awal dari itemData
        title: itemData.title || '',
        category: itemData.category || Object.keys(categoryOptions)[0] || '',
        
        // Input untuk file baru (nullable di update)
        image_file: null, 
        
        // Flag untuk menghapus gambar yang sudah ada (sesuai logika controller)
        _delete_image: false, 
        
        // Method Spoofing untuk UPDATE (sesuai Controller)
        _method: 'put', 
    });

    const imageRef = useRef(null);
    const [previewUrl, setPreviewUrl] = useState(itemData.current_image_url || null);

    // --- Image Handlers & Cleanup ---
    
    // Memperbarui pratinjau saat image_file atau _delete_image berubah
    useEffect(() => {
        let url = itemData.current_image_url;

        // 1. Jika ada file baru yang dipilih, buat URL pratinjau baru
        if (data.image_file) {
            url = URL.createObjectURL(data.image_file);
        } 
        // 2. Jika tidak ada file baru DAN flag hapus dicentang, hapus pratinjau
        else if (data._delete_image) {
            url = null;
        } 
        // 3. Jika tidak ada file baru dan tidak ada penghapusan, gunakan URL lama
        else {
            url = itemData.current_image_url;
        }

        setPreviewUrl(url);

        // Cleanup function
        return () => {
            if (data.image_file) {
                URL.revokeObjectURL(url);
            }
        };
    }, [data.image_file, data._delete_image, itemData.current_image_url]);


    const handleFileChange = (e) => {
        setData(prev => ({ 
            ...prev, 
            image_file: e.target.files[0],
            // Jika memilih file baru, batalkan permintaan hapus gambar lama
            _delete_image: false
        }));
        clearErrors('image_file');
    };
    
    const clearNewImage = () => {
        setData(prev => ({ ...prev, image_file: null }));
        if (imageRef.current) {
            imageRef.current.value = null;
        }
        clearErrors('image_file');
    };

    const handleCheckboxDeleteChange = (e) => {
        setData(prev => ({ 
            ...prev, 
            _delete_image: e.target.checked, 
            // Jika mencentang hapus, kosongkan input file baru
            image_file: null 
        }));
        if (imageRef.current) {
            imageRef.current.value = null;
        }
    };


    // --- Form Handler ---

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

        Swal.fire({
            title: 'Konfirmasi Perbarui Foto Galeri',
            text: "Apakah Anda yakin ingin menyimpan perubahan pada foto ini?",
            icon: 'question',
            showCancelButton: true,
            // DIUBAH KE WARNA BIRU
            confirmButtonColor: '#3B82F6', // blue-500
            cancelButtonColor: '#EF4444', // red-500
            confirmButtonText: 'Ya, Perbarui',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Mengirim ke route update dengan ID item
                post(route('admin.kampus.galeri.update', itemData.id), { 
                    onSuccess: () => {
                        // Tidak perlu reset data form, cukup tampilkan sukses
                        Swal.fire('Berhasil!', 'Foto galeri telah berhasil diperbarui.', 'success');
                    },
                    onError: (errors) => {
                        console.error("Gagal memperbarui foto galeri:", errors);
                        Swal.fire('Gagal!', 'Terjadi kesalahan saat menyimpan data. Periksa kembali input Anda.', 'error');
                    },
                    forceFormData: true, // Wajib untuk upload file dan method spoofing
                });
            }
        });
    };
    
    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Edit Foto Galeri: {itemData.title}</h2>}
        >
            <Head title={`Edit Foto Galeri: ${itemData.title}`} />

            <div className="max-w-3xl mx-auto sm:px-6 lg:px-8 py-12">
                <div className="bg-white overflow-hidden shadow-xl sm:rounded-xl p-8">
                    
                    <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">
                            {/* Aksen Biru pada Ikon */}
                            <FontAwesomeIcon icon={faImages} className="mr-3 text-blue-600" />
                            Formulir Edit Foto Galeri
                        </h3>
                        <Link
                            href={route('admin.kampus.galeri.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 Galeri
                        </Link>
                    </div>

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

                        {/* 2. Kategori (CATEGORY) */}
                        <div>
                            <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                <FontAwesomeIcon icon={faTag} className="w-3 h-3 mr-2" />
                                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-blue-500 focus:border-blue-500 transition duration-150 appearance-none`}
                                required
                            >
                                {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. Unggah Gambar Utama (image_file) */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                <FontAwesomeIcon icon={faCamera} className="w-4 h-4 mr-2" />
                                Ganti / Pilih Foto Galeri Baru
                            </label>
                            <div className="flex items-center space-x-4">
                                <input
                                    ref={imageRef}
                                    id="image_file"
                                    type="file"
                                    onChange={handleFileChange}
                                    className={`block w-full text-sm text-gray-900 border ${errors.image_file ? 'border-red-500' : 'border-gray-300'} rounded-lg cursor-pointer bg-gray-50 focus:outline-none p-2 transition duration-150`}
                                    accept="image/*"
                                />
                                {data.image_file && (
                                    <button
                                        type="button"
                                        onClick={clearNewImage}
                                        className="p-2 text-red-600 hover:text-red-800 transition duration-150 rounded-full"
                                        aria-label="Batalkan Gambar Baru"
                                    >
                                        <FontAwesomeIcon icon={faTimes} className="w-5 h-5" />
                                    </button>
                                )}
                            </div>
                            {errors.image_file && <p className="mt-2 text-sm text-red-600">{errors.image_file}</p>}

                            {/* Checkbox Hapus Gambar Saat Ini */}
                            {itemData.image_path && (
                                <div className="mt-3 flex items-center">
                                    <input
                                        id="_delete_image"
                                        type="checkbox"
                                        checked={data._delete_image}
                                        onChange={handleCheckboxDeleteChange}
                                        className="h-4 w-4 text-red-600 border-gray-300 rounded focus:ring-red-500"
                                    />
                                    <label htmlFor="_delete_image" className="ml-2 text-sm font-medium text-red-600 flex items-center">
                                        <FontAwesomeIcon icon={faTrash} className="w-3 h-3 mr-1" />
                                        Hapus Foto Galeri Saat Ini
                                    </label>
                                </div>
                            )}

                            {/* Pratinjau Gambar */}
                            {previewUrl && (
                                <div className="mt-4 p-2 border border-gray-200 rounded-lg bg-gray-50">
                                    <p className="text-xs text-gray-500 mb-2 font-semibold">
                                        {data.image_file ? 'Pratinjau Foto Baru:' : 'Foto Saat Ini:'}
                                    </p>
                                    <img 
                                        src={previewUrl} 
                                        alt="Pratinjau Foto Galeri" 
                                        className="w-full max-h-64 object-cover rounded-lg shadow-md"
                                    />
                                </div>
                            )}

                            {!previewUrl && !data._delete_image && itemData.image_path && (
                                <div className="mt-4 text-sm text-yellow-600 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                                    ⚠️ File gambar tidak ditemukan di server, tetapi path masih tersimpan di database. Mengunggah gambar baru disarankan.
                                </div>
                            )}

                        </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 ${
                                    // Aksen Biru pada tombol simpan
                                    processing 
                                    ? 'bg-blue-400 cursor-not-allowed' 
                                    : '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={faSave} className="w-4 h-4 mr-2" />
                                {processing ? 'Memperbarui...' : 'Perbarui Foto'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </AdminKampusLayout>
    );
}