import React, { useState, useEffect, useCallback } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, useForm, Link } from '@inertiajs/react'; 
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faSave, faArrowLeft, faImage, faTimes, faUpload, faToggleOn
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2'; 


// ========================================================================
// --- Komponen Utama: Brosur Create Page ---
// ========================================================================

/**
 * Komponen untuk membuat entri Brosur baru.
 * @param {{ auth: Object, errors: Object }} props
 */
export default function BrosurCreate({ auth, errors }) {
    // State untuk menyimpan URL pratinjau gambar depan dan belakang yang baru dipilih
    const [imageFrontPreview, setImageFrontPreview] = useState(null);
    const [imageBackPreview, setImageBackPreview] = useState(null);

    // Inisialisasi useForm
    const { data, setData, post, processing, reset } = useForm({
        // Data utama (field title telah dihapus)
        
        // FIELD UNTUK FILE UPLOAD (Dipecah menjadi depan dan belakang)
        image_front_file: null, // FILE DEPAN
        image_back_file: null,  // FILE BELAKANG
        
        // FIELD STATUS AKTIF
        is_active: true, // Default aktif
    });

    const headerText = 'Unggah Brosur Baru';

    // Efek untuk membuat pratinjau saat file gambar depan (image_front_file) berubah
    useEffect(() => {
        if (data.image_front_file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImageFrontPreview(reader.result);
            };
            reader.readAsDataURL(data.image_front_file);
        } else {
            setImageFrontPreview(null);
        }
    }, [data.image_front_file]);
    
    // Efek untuk membuat pratinjau saat file gambar belakang (image_back_file) berubah
    useEffect(() => {
        if (data.image_back_file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImageBackPreview(reader.result);
            };
            reader.readAsDataURL(data.image_back_file);
        } else {
            setImageBackPreview(null);
        }
    }, [data.image_back_file]);


    // Handler untuk input sederhana (hanya tersisa is_active)
    const handleInputChange = (e) => {
        const { name, value, type, checked } = e.target;
        setData(name, type === 'checkbox' ? checked : value);
    };

    /**
     * Handler UNTUK FILE GAMBAR (General)
     */
    const handleFileChange = (e, fieldName) => {
        const file = e.target.files[0];
        setData(fieldName, file || null);
    };
    
    /**
     * Handler untuk menghapus gambar yang baru dipilih (General)
     * Menggunakan useCallback untuk stabilitas fungsi
     */
    const handleRemoveFile = useCallback((fieldName) => {
        // Reset data form
        setData(fieldName, null);

        // Penting: Reset input file agar pengguna bisa memilih file yang sama lagi
        const inputElement = document.getElementById(fieldName);
        if (inputElement) {
            inputElement.value = '';
        }
    }, [setData]); // Tambahkan setData ke dependencies

    
    // Submit Form
    const submit = (e) => {
        e.preventDefault();
        
        // VALIDASI SISI KLIEN: Pastikan kedua file gambar sudah dipilih
        if (!data.image_front_file || !data.image_back_file) {
            Swal.fire({
                icon: 'warning',
                title: 'Perhatian!',
                text: 'Harap unggah **Halaman Depan** dan **Halaman Belakang** brosur.', 
                confirmButtonColor: '#FBBF24', 
            });
            return;
        }

        // VALIDASI SISI KLIEN: Judul/Keterangan Singkat telah dihapus dari sini.

        // Menggunakan rute STORE
        post(route('admin.kampus.brosur.store'), { 
            // PENTING: forceFormData HARUS TRUE untuk file upload
            forceFormData: true, 
            
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: 'Data Brosur berhasil diunggah.', 
                    confirmButtonColor: '#4F46E5', 
                }).then(() => {
                    // Reset semua state form dan pratinjau
                    reset(); 
                    // Panggil fungsi remove file untuk membersihkan input file DOM
                    handleRemoveFile('image_front_file'); 
                    handleRemoveFile('image_back_file');
                });
            },
            onError: (err) => {
                // LOG LEBIH RINCI: Cek objek error yang dikembalikan dari Laravel
                console.error("Error submitting form:", err, { submittedData: data }); 
                
                // Cek apakah ada pesan error dari Laravel (misalnya 422 Unprocessable Entity)
                let errorMessage = 'Terjadi kesalahan saat menyimpan data. Periksa kembali isian Anda.';
                let errorDetails = '';
                
                if (err && Object.keys(err).length > 0) {
                    // Jika ada error validasi dari backend, buat pesan lebih spesifik
                    errorMessage = 'Terdapat kesalahan validasi pada formulir. Silakan periksa kolom yang ditandai.';
                    // Mencoba mendapatkan pesan error pertama untuk ditampilkan di Swal
                    const firstErrorKey = Object.keys(err)[0];
                    errorDetails = err[firstErrorKey];
                    if (Array.isArray(errorDetails) && errorDetails.length > 0) {
                         errorMessage = errorDetails[0];
                    } else if (typeof errorDetails === 'string') {
                         errorMessage = errorDetails;
                    }
                    
                    if (err.image_front_file || err.image_back_file) {
                        errorMessage = 'Gagal mengunggah file. Pastikan format file adalah JPG/PNG dan ukurannya tidak terlalu besar.';
                    }

                }

                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: errorMessage,
                    confirmButtonColor: '#DC2626', 
                });
            }
        });
    };

    // ----------------------------------------------------
    // --- Render Component ---
    // ----------------------------------------------------

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

            <div className="max-w-7xl mx-auto sm:px-6 lg:px-8 py-12">
                
                <form onSubmit={submit} className="bg-white overflow-hidden shadow-xl sm:rounded-lg p-8">
                    
                    {/* Header Formulir */}
                    <div className="flex justify-between items-center mb-8 border-b pb-4">
                        <h3 className="text-2xl font-bold text-indigo-700 flex items-center">
                            <FontAwesomeIcon icon={faUpload} className="mr-3 w-6 h-6" />
                            {headerText}
                        </h3>
                        <div className="flex space-x-3">
                            <Link
                                href={route('admin.kampus.brosur.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 ease-in-out duration-150"
                            >
                                <FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3 mr-2" />
                                Kembali
                            </Link>
                            <button
                                type="submit"
                                disabled={processing}
                                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 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 transition ease-in-out duration-150 shadow-md ${processing ? 'opacity-75' : ''}`}
                            >
                                <FontAwesomeIcon icon={faSave} className="w-3 h-3 mr-2" />
                                {processing ? 'Menyimpan...' : 'Unggah Brosur'} 
                            </button>
                        </div>
                    </div>
                    
                    
                    {/* ======================= BAGIAN 1: UPLOAD FILE GAMBAR DEPAN & BELAKANG ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3 flex items-center">
                        <FontAwesomeIcon icon={faImage} className="mr-2" />
                        Unggah File Gambar Brosur (Depan & Belakang) <span className="text-red-500">*</span>
                    </h4>
                    <p className="text-sm text-gray-500 mb-6">Unggah gambar terpisah untuk halaman depan dan halaman belakang brosur Anda.</p>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        
                        {/* INPUT GAMBAR DEPAN */}
                        <div>
                            <label htmlFor="image_front_file" className="block text-sm font-bold text-gray-700 mb-2">
                                1. Halaman Depan Brosur <span className="text-red-500">*</span>
                            </label>
                            <input
                                id="image_front_file"
                                type="file"
                                name="image_front_file"
                                accept="image/jpeg,image/png,image/jpg" // Lebih spesifik untuk format
                                onChange={(e) => handleFileChange(e, 'image_front_file')}
                                required
                                className={`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-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100 ${errors.image_front_file ? 'border-red-500' : ''}`}
                            />
                            {/* Pastikan error dari backend ditampilkan di sini */}
                            {errors.image_front_file && <div className="text-xs text-red-600 mt-1">{errors.image_front_file}</div>}
                            
                            {/* Pratinjau Gambar Depan */}
                            {imageFrontPreview ? (
                                <div className="mt-4 p-4 border border-gray-200 rounded-lg bg-gray-50 relative">
                                    <p className="text-xs font-medium text-gray-600 mb-2">Pratinjau Halaman Depan:</p>
                                    <img 
                                        src={imageFrontPreview} 
                                        alt="Pratinjau Brosur Depan" 
                                        // Gunakan max-h-60 atau nilai lain yang sesuai
                                        className="w-full h-auto rounded-lg object-contain max-h-60" 
                                    />
                                    <button
                                        type="button"
                                        onClick={() => handleRemoveFile('image_front_file')}
                                        className="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-700 transition shadow"
                                        title="Hapus Gambar Depan"
                                    >
                                        <FontAwesomeIcon icon={faTimes} className="w-3 h-3" />
                                    </button>
                                </div>
                            ) : (
                                <div className="mt-4 p-4 border border-dashed border-gray-300 rounded-lg bg-gray-50 text-center">
                                    <FontAwesomeIcon icon={faImage} className="w-6 h-6 text-gray-400 mb-2" />
                                    <p className="text-sm text-gray-500">Belum ada gambar depan yang dipilih.</p>
                                </div>
                            )}
                        </div>
                        
                        {/* INPUT GAMBAR BELAKANG */}
                        <div>
                            <label htmlFor="image_back_file" className="block text-sm font-bold text-gray-700 mb-2">
                                2. Halaman Belakang Brosur <span className="text-red-500">*</span>
                            </label>
                            <input
                                id="image_back_file"
                                type="file"
                                name="image_back_file"
                                accept="image/jpeg,image/png,image/jpg" // Lebih spesifik untuk format
                                onChange={(e) => handleFileChange(e, 'image_back_file')}
                                required
                                className={`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-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100 ${errors.image_back_file ? 'border-red-500' : ''}`}
                            />
                            {/* Pastikan error dari backend ditampilkan di sini */}
                            {errors.image_back_file && <div className="text-xs text-red-600 mt-1">{errors.image_back_file}</div>}
                            
                            {/* Pratinjau Gambar Belakang */}
                            {imageBackPreview ? (
                                <div className="mt-4 p-4 border border-gray-200 rounded-lg bg-gray-50 relative">
                                    <p className="text-xs font-medium text-gray-600 mb-2">Pratinjau Halaman Belakang:</p>
                                    <img 
                                        src={imageBackPreview} 
                                        alt="Pratinjau Brosur Belakang" 
                                        className="w-full h-auto rounded-lg object-contain max-h-60"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => handleRemoveFile('image_back_file')}
                                        className="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-700 transition shadow"
                                        title="Hapus Gambar Belakang"
                                    >
                                        <FontAwesomeIcon icon={faTimes} className="w-3 h-3" />
                                    </button>
                                </div>
                            ) : (
                                <div className="mt-4 p-4 border border-dashed border-gray-300 rounded-lg bg-gray-50 text-center">
                                    <FontAwesomeIcon icon={faImage} className="w-6 h-6 text-gray-400 mb-2" />
                                    <p className="text-sm text-gray-500">Belum ada gambar belakang yang dipilih.</p>
                                </div>
                            )}
                        </div>
                        
                    </div>
                    {/* AKHIR FIELD UPLOAD GAMBAR */}
                    
                    
                    <hr className="my-8" />
                    
                    {/* ======================= BAGIAN 2: INFORMASI PELENGKAP ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3">Informasi Pelengkap</h4>

                    {/* Judul/Keterangan - TELAH DIHAPUS */}
                    {/* Field Judul/Keterangan sudah dihapus sesuai permintaan */}

                    {/* Status Aktif */}
                    <div className="mb-8 p-4 border rounded-lg bg-gray-50">
                        <label htmlFor="is_active" className="block text-sm font-medium text-gray-700 mb-2 items-center">
                            <FontAwesomeIcon icon={faToggleOn} className="mr-2" />
                            Status Publikasi
                        </label>
                        <div className="flex items-center">
                            <input
                                id="is_active"
                                type="checkbox"
                                name="is_active"
                                checked={data.is_active}
                                onChange={handleInputChange}
                                className={`mr-2 h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500`}
                            />
                            <label htmlFor="is_active" className="text-sm font-medium text-gray-700">
                                Aktifkan Brosur ini (Centang untuk ditampilkan di website).
                            </label>
                        </div>
                        <p className="text-xs text-gray-500 mt-2">
                            **Perhatian:** Hanya satu Brosur yang bisa aktif dalam satu waktu. Jika Anda mengaktifkan yang ini, struktur sebelumnya akan dinonaktifkan secara otomatis.
                        </p>
                        {errors.is_active && <div className="text-xs text-red-600 mt-1">{errors.is_active}</div>}
                    </div>


                    <div className="flex justify-end pt-4 border-t">
                        <button
                            type="submit"
                            disabled={processing}
                            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 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 transition ease-in-out duration-150 shadow-md ${processing ? 'opacity-75' : ''}`}
                        >
                            <FontAwesomeIcon icon={faSave} className="w-3 h-3 mr-2" />
                            {processing ? 'Menyimpan...' : 'Unggah Brosur'} 
                        </button>
                    </div>

                </form>
            </div>
        </AdminKampusLayout>
    );
}
