import React, { useState, useEffect } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
// Import Link, Head, useForm dari Inertia.js
import { Head, useForm, Link } from '@inertiajs/react'; 
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faSave, faArrowLeft, faPlus, faTrash, faHistory, faQuoteLeft, faBookOpen, 
    faImage, faTimes
} from '@fortawesome/free-solid-svg-icons';
// Import SweetAlert2
import Swal from 'sweetalert2'; 


/**
 * Komponen pembantu untuk menampilkan Milestones.
 * Milestones adalah struktur data { year: string, title: string }.
 */
const MilestoneInput = ({ index, milestone, onMilestoneChange, onMilestoneRemove, errors }) => {
    const errorPrefix = `content_details.milestones.${index}`;
    
    return (
        <div className="flex space-x-3 mb-3 p-3 bg-gray-50 rounded-lg border border-gray-200 items-start">
            {/* Tahun (Year) */}
            <div className="w-1/4">
                <input
                    type="text"
                    placeholder="Tahun (e.g., 1990)"
                    value={milestone.year || ''}
                    onChange={(e) => onMilestoneChange(index, 'year', e.target.value)}
                    className={`w-full text-sm border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors[`${errorPrefix}.year`] ? 'border-red-500' : ''}`}
                />
                {errors[`${errorPrefix}.year`] && (
                    <div className="text-xs text-red-600 mt-1">{errors[`${errorPrefix}.year`]}</div>
                )}
            </div>
            
            {/* Judul/Deskripsi Milestone */}
            <div className="flex-grow">
                <input
                    type="text"
                    placeholder="Judul Milestone/Peristiwa Penting"
                    value={milestone.title || ''}
                    onChange={(e) => onMilestoneChange(index, 'title', e.target.value)}
                    className={`w-full text-sm border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors[`${errorPrefix}.title`] ? 'border-red-500' : ''}`}
                />
                {errors[`${errorPrefix}.title`] && (
                    <div className="text-xs text-red-600 mt-1">{errors[`${errorPrefix}.title`]}</div>
                )}
            </div>

            {/* Tombol Hapus */}
            <button
                type="button"
                onClick={() => onMilestoneRemove(index)}
                className="text-red-500 hover:text-red-700 transition flex-shrink-0 mt-2"
                title="Hapus Milestone"
            >
                <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
            </button>
        </div>
    );
};


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

/**
 * @param {{ auth: Object, errors: Object }} props
 */
export default function SejarahCreate({ auth, errors }) {
    // State untuk menyimpan URL pratinjau gambar yang baru dipilih
    const [imagePreview, setImagePreview] = useState(null);

    // Inisialisasi useForm hanya dengan nilai kosong untuk mode Create
    const { data, setData, post, processing, recentlySuccessful, reset } = useForm({
        // Data utama (semua mulai dari nilai kosong)
        title: '',
        subtitle: '',
        
        // FIELD UNTUK FILE UPLOAD
        image_file: null, 
        
        pull_quote: '',
        
        // Data Array (Paragraf Utama)
        paragraphs: [''], // Mulai dengan satu input kosong

        // Data JSON/Array (Content Details)
        content_details: {
            milestones: [{ year: '', title: '' }], // Mulai dengan satu input kosong
            extraParagraphs: [''], // Mulai dengan satu input kosong
        }
    });

    const headerText = 'Buat Sejarah Kampus Baru';

    // Efek untuk membuat pratinjau saat image_file berubah
    useEffect(() => {
        if (data.image_file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImagePreview(reader.result);
            };
            reader.readAsDataURL(data.image_file);
        } else {
            setImagePreview(null);
        }
    }, [data.image_file]);


    // Handler untuk input sederhana (title, subtitle, pull_quote)
    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setData(name, value);
    };

    // Handler UNTUK FILE GAMBAR
    const handleImageChange = (e) => {
        const file = e.target.files[0];
        setData('image_file', file || null);
    };
    
    // Handler untuk menghapus gambar yang baru dipilih
    const handleRemoveImage = () => {
        setData('image_file', null);
        // Penting: Reset input file agar pengguna bisa memilih file yang sama lagi
        document.getElementById('image_file').value = null; 
    };
    
    // Handler untuk Paragraphs Utama (Bagian atas) - Logika tetap sama
    const handleParagraphChange = (index, value) => {
        const newParagraphs = data.paragraphs.map((p, i) => (i === index ? value : p));
        setData('paragraphs', newParagraphs);
    };

    const handleAddParagraph = () => {
        setData('paragraphs', [...data.paragraphs, '']);
    };

    const handleRemoveParagraph = (index) => {
        if (data.paragraphs.length > 1) {
            setData('paragraphs', data.paragraphs.filter((_, i) => i !== index));
        } else {
            // Jika hanya tersisa satu, hapus isinya saja
            setData('paragraphs', ['']);
        }
    };

    // Handler untuk Milestones (di dalam content_details) - Logika tetap sama
    const handleMilestoneChange = (index, field, value) => {
        const newMilestones = data.content_details.milestones.map((m, i) => (
            i === index ? { ...m, [field]: value } : m
        ));
        setData('content_details', { ...data.content_details, milestones: newMilestones });
    };

    const handleAddMilestone = () => {
        setData('content_details', { 
            ...data.content_details, 
            milestones: [...data.content_details.milestones, { year: '', title: '' }] 
        });
    };

    const handleRemoveMilestone = (index) => {
        if (data.content_details.milestones.length > 1) {
            setData('content_details', {
                ...data.content_details,
                milestones: data.content_details.milestones.filter((_, i) => i !== index),
            });
        } else {
             setData('content_details', { ...data.content_details, milestones: [{ year: '', title: '' }] });
        }
    };
    
    // Handler untuk Extra Paragraphs (Konten Tambahan) - Logika tetap sama
    const handleExtraParagraphChange = (index, value) => {
        const newExtraParagraphs = data.content_details.extraParagraphs.map((p, i) => (i === index ? value : p));
        setData('content_details', { ...data.content_details, extraParagraphs: newExtraParagraphs });
    };

    const handleAddExtraParagraph = () => {
        setData('content_details', { 
            ...data.content_details, 
            extraParagraphs: [...data.content_details.extraParagraphs, ''] 
        });
    };

    const handleRemoveExtraParagraph = (index) => {
        if (data.content_details.extraParagraphs.length > 1) {
            setData('content_details', {
                ...data.content_details,
                extraParagraphs: data.content_details.extraParagraphs.filter((_, i) => i !== index),
            });
        } else {
            setData('content_details', { ...data.content_details, extraParagraphs: [''] });
        }
    };

    // Tentukan URL gambar yang akan ditampilkan (hanya dari file baru yang dipilih)
    const currentImageUrl = imagePreview; 
    
    // Submit Form
    const submit = (e) => {
        e.preventDefault();
        
        // Selalu gunakan rute STORE untuk mode Create
        post(route('admin.kampus.sejarah.store'), {
            forceFormData: true, // Pastikan dikirim sebagai FormData karena ada file
            
            // Tambahkan SweetAlert pada handler keberhasilan (onSuccess) dan kegagalan (onError)
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: 'Data Sejarah Kampus berhasil disimpan.',
                    confirmButtonColor: '#4F46E5', // Warna indigo
                }).then(() => {
                    // Opsional: Reset form setelah berhasil jika ingin membuat data baru lagi
                    reset(); 
                    handleRemoveImage(); // Reset preview gambar juga
                });
            },
            onError: (err) => {
                 console.error("Error submitting form:", err);
                 Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: 'Terjadi kesalahan saat menyimpan data. Periksa kembali isian Anda.',
                    confirmButtonColor: '#DC2626', // Warna merah
                });
            }
        });
    };

    // ----------------------------------------------------
    // --- 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={faBookOpen} className="mr-3 w-6 h-6" />
                            {headerText}
                        </h3>
                        <div className="flex space-x-3">
                            <Link
                                href={route('admin.kampus.sejarah.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...' : 'Simpan Sejarah'}
                            </button>
                        </div>
                    </div>

                    {/* Catatan: Notifikasi Inertia (recentlySuccessful) akan digantikan oleh SweetAlert */}
                    {/* {recentlySuccessful && (
                        <div className="mb-4 p-3 bg-green-100 text-green-700 border border-green-200 rounded-lg">
                            ✅ Data berhasil disimpan!
                        </div>
                    )} */}
                    
                    {/* ======================= BAGIAN 1: INFORMASI DASAR ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3">Informasi Utama</h4>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                        {/* Judul */}
                        <div>
                            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">Judul Sejarah <span className="text-red-500">*</span></label>
                            <input
                                id="title"
                                type="text"
                                name="title"
                                value={data.title}
                                onChange={handleInputChange}
                                className={`w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors.title ? 'border-red-500' : ''}`}
                            />
                            {errors.title && <div className="text-xs text-red-600 mt-1">{errors.title}</div>}
                        </div>
                        
                        {/* Subtitle */}
                        <div>
                            <label htmlFor="subtitle" className="block text-sm font-medium text-gray-700 mb-1">Sub Judul</label>
                            <input
                                id="subtitle"
                                type="text"
                                name="subtitle"
                                value={data.subtitle}
                                onChange={handleInputChange}
                                className={`w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors.subtitle ? 'border-red-500' : ''}`}
                            />
                            {errors.subtitle && <div className="text-xs text-red-600 mt-1">{errors.subtitle}</div>}
                        </div>
                    </div>

                    {/* FIELD UPLOAD GAMBAR */}
                    <div className="mb-6">
                        <label htmlFor="image_file" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                            <FontAwesomeIcon icon={faImage} className="mr-2 w-3 h-3 text-gray-500" />
                            Upload Gambar Utama
                        </label>
                        <div className="flex items-center space-x-3">
                            <input
                                id="image_file"
                                type="file"
                                name="image_file"
                                accept="image/*"
                                onChange={handleImageChange}
                                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_file ? 'border-red-500' : ''}`}
                            />
                        </div>
                        {errors.image_file && <div className="text-xs text-red-600 mt-1">{errors.image_file}</div>}
                        
                        {/* Pratinjau Gambar & Tombol Hapus (Hanya untuk gambar yang baru diupload) */}
                        {currentImageUrl ? (
                            <div className="mt-4 p-4 border border-gray-200 rounded-lg bg-gray-50 max-w-sm relative">
                                <p className="text-xs font-medium text-gray-600 mb-2">Pratinjau Gambar:</p>
                                <img 
                                    src={currentImageUrl} 
                                    alt="Pratinjau Gambar" 
                                    className="w-full h-auto rounded-lg object-cover max-h-60"
                                />
                                <button
                                    type="button"
                                    onClick={handleRemoveImage}
                                    className="absolute top-2 right-2 p-1 bg-red-500 text-white rounded-full hover:bg-red-700 transition shadow"
                                    title="Hapus Gambar"
                                >
                                    <FontAwesomeIcon icon={faTimes} className="w-3 h-3" />
                                </button>
                                <p className="text-xs text-indigo-600 mt-2">Gambar ini akan diunggah.</p>
                            </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 yang dipilih.</p>
                            </div>
                        )}
                    </div>
                    {/* AKHIR FIELD UPLOAD GAMBAR */}
                    
                    
                    {/* Pull Quote */}
                    <div className="mb-8">
                        <label htmlFor="pull_quote" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                             <FontAwesomeIcon icon={faQuoteLeft} className="mr-2 w-3 h-3 text-gray-500" />
                            Kutipan Menarik (Pull Quote)
                        </label>
                        <textarea
                            id="pull_quote"
                            name="pull_quote"
                            rows="2"
                            value={data.pull_quote}
                            onChange={handleInputChange}
                            placeholder="Kutipan singkat yang menarik dari sejarah kampus..."
                            className={`w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors.pull_quote ? 'border-red-500' : ''}`}
                        />
                        {errors.pull_quote && <div className="text-xs text-red-600 mt-1">{errors.pull_quote}</div>}
                    </div>


                    {/* ======================= BAGIAN 2: PARAGRAF UTAMA ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3">Paragraf Konten Utama <span className="text-red-500">*</span></h4>
                    <p className="text-sm text-gray-500 mb-4">Susun sejarah kampus Anda dalam paragraf-paragraf utama.</p>
                    
                    {data.paragraphs.map((paragraph, index) => (
                        <div key={index} className="flex space-x-3 mb-4 items-start">
                            <textarea
                                rows="3"
                                value={paragraph}
                                onChange={(e) => handleParagraphChange(index, e.target.value)}
                                placeholder={`Paragraf Konten Utama ${index + 1}`}
                                className={`flex-grow border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors[`paragraphs.${index}`] ? 'border-red-500' : ''}`}
                            />
                            <button
                                type="button"
                                onClick={() => handleRemoveParagraph(index)}
                                className={`text-red-500 hover:text-red-700 transition mt-2 ${data.paragraphs.length === 1 && index === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}
                                title="Hapus Paragraf"
                                disabled={data.paragraphs.length === 1 && index === 0}
                            >
                                <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
                            </button>
                        </div>
                    ))}

                    <button
                        type="button"
                        onClick={handleAddParagraph}
                        className="inline-flex items-center px-3 py-1 bg-gray-100 border border-gray-300 rounded-lg font-medium text-xs text-gray-700 hover:bg-gray-200 transition mb-8"
                    >
                        <FontAwesomeIcon icon={faPlus} className="w-3 h-3 mr-2" />
                        Tambah Paragraf
                    </button>
                    {errors.paragraphs && <div className="text-xs text-red-600 mt-1 mb-8">{errors.paragraphs}</div>}
                    
                    {/* ======================= BAGIAN 3: DETAIL KONTEN (MILESTONES) ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3 flex items-center">
                        <FontAwesomeIcon icon={faHistory} className="mr-2" />
                        Garis Waktu (Milestones)
                    </h4>
                    <p className="text-sm text-gray-500 mb-4">Tambahkan peristiwa penting dalam sejarah kampus Anda.</p>

                    {data.content_details.milestones.map((milestone, index) => (
                        <MilestoneInput 
                            key={index}
                            index={index}
                            milestone={milestone}
                            onMilestoneChange={handleMilestoneChange}
                            onMilestoneRemove={handleRemoveMilestone}
                            errors={errors}
                        />
                    ))}

                    <button
                        type="button"
                        onClick={handleAddMilestone}
                        className="inline-flex items-center px-3 py-1 bg-indigo-50 border border-indigo-300 rounded-lg font-medium text-xs text-indigo-700 hover:bg-indigo-100 transition mb-8"
                    >
                        <FontAwesomeIcon icon={faPlus} className="w-3 h-3 mr-2" />
                        Tambah Milestone
                    </button>
                    {errors['content_details.milestones'] && <div className="text-xs text-red-600 mt-1">{errors['content_details.milestones']}</div>}

                    {/* ======================= BAGIAN 4: PARAGRAF TAMBAHAN ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3 flex items-center">
                        <FontAwesomeIcon icon={faBookOpen} className="mr-2" />
                        Paragraf Konten Tambahan
                    </h4>
                    <p className="text-sm text-gray-500 mb-4">Paragraf yang muncul setelah Garis Waktu.</p>
                    
                    {data.content_details.extraParagraphs.map((paragraph, index) => (
                        <div key={`extra-${index}`} className="flex space-x-3 mb-4 items-start">
                            <textarea
                                rows="3"
                                value={paragraph}
                                onChange={(e) => handleExtraParagraphChange(index, e.target.value)}
                                placeholder={`Paragraf Tambahan ${index + 1}`}
                                className={`flex-grow border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors[`content_details.extraParagraphs.${index}`] ? 'border-red-500' : ''}`}
                            />
                            <button
                                type="button"
                                onClick={() => handleRemoveExtraParagraph(index)}
                                className={`text-red-500 hover:text-red-700 transition mt-2 ${data.content_details.extraParagraphs.length === 1 && index === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}
                                title="Hapus Paragraf Tambahan"
                                disabled={data.content_details.extraParagraphs.length === 1 && index === 0}
                            >
                                <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
                            </button>
                        </div>
                    ))}

                    <button
                        type="button"
                        onClick={handleAddExtraParagraph}
                        className="inline-flex items-center px-3 py-1 bg-gray-100 border border-gray-300 rounded-lg font-medium text-xs text-gray-700 hover:bg-gray-200 transition mb-8"
                    >
                        <FontAwesomeIcon icon={faPlus} className="w-3 h-3 mr-2" />
                        Tambah Paragraf Tambahan
                    </button>
                    {errors['content_details.extraParagraphs'] && <div className="text-xs text-red-600 mt-1 mb-8">{errors['content_details.extraParagraphs']}</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...' : 'Simpan Sejarah'}
                        </button>
                    </div>

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