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


/**
 * Komponen pembantu untuk menampilkan input Array (Misi/Tujuan).
 * (Fungsi yang sama seperti di Create.jsx, diulang agar file independen)
 */
const ArrayTextInput = ({ index, value, placeholder, onChange, onRemove, errors, errorPrefix }) => {
    // Menghindari penghapusan item pertama hanya jika isinya kosong.
    const isFirstItem = index === 0;
    const isOnlyOneEmptyItem = isFirstItem && Array.isArray(value) && value.length === 1 && value[0] === '';

    return (
        <div className="flex space-x-3 mb-3 items-start">
            <div className="text-gray-500 font-bold mt-2 w-6 flex-shrink-0 text-center">
                {index + 1}.
            </div>
            
            <textarea
                rows="2"
                value={value || ''}
                onChange={(e) => onChange(index, e.target.value)}
                placeholder={`${placeholder} ${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[`${errorPrefix}.${index}`] ? 'border-red-500' : ''}`}
            />
            
            <button
                type="button"
                onClick={() => onRemove(index)}
                className="text-red-500 hover:text-red-700 transition mt-2"
                title={`Hapus ${placeholder}`}
            >
                <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
            </button>

            {errors[`${errorPrefix}.${index}`] && (
                <div className="text-xs text-red-600 mt-1">{errors[`${errorPrefix}.${index}`]}</div>
            )}
        </div>
    );
};


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

/**
 * @param {{ auth: Object, errors: Object, visiMisi: Object }} props
 */
export default function VisiMisiEdit({ auth, errors, visiMisi }) {
    
    // Fungsi helper untuk memastikan array memiliki minimal 1 item (untuk form input)
    const normalizeArray = (arr) => {
        // Jika null/undefined atau array kosong, kembalikan array dengan satu string kosong
        if (!arr || arr.length === 0) {
            return [''];
        }
        return arr;
    };
    
    // Inisialisasi useForm untuk mode EDIT dengan data yang sudah ada
    const { data, setData, put, processing } = useForm({
        title: visiMisi.title ?? '',
        visi: visiMisi.visi ?? '',
        // Pastikan misi dan tujuan selalu berupa array dengan minimal satu elemen kosong jika null
        misi: normalizeArray(visiMisi.misi),
        tujuan: normalizeArray(visiMisi.tujuan), 
    });

    const headerText = 'Edit Visi, Misi, & Tujuan Kampus';

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setData(name, value);
    };

    /**
     * Handler generik untuk Array Input (Misi atau Tujuan)
     */
    const handleArrayChange = (fieldName, index, value) => {
        const newArray = data[fieldName].map((p, i) => (i === index ? value : p));
        setData(fieldName, newArray);
    };

    /**
     * Handler generik untuk menambahkan item Array (Misi atau Tujuan)
     */
    const handleAddArrayItem = (fieldName) => {
        setData(fieldName, [...data[fieldName], '']);
    };

    /**
     * Handler generik untuk menghapus item Array (Misi atau Tujuan)
     */
    const handleRemoveArrayItem = (fieldName, index) => {
        const currentArray = data[fieldName];
        
        if (currentArray.length > 1) {
            setData(fieldName, currentArray.filter((_, i) => i !== index));
        } else if (currentArray.length === 1) {
            // Jika hanya satu item, kosongkan isinya
            setData(fieldName, ['']);
        }
    };


    // Fungsi pembersih data array sebelum submit
    const cleanDataForSubmission = (formData) => {
        const cleanMisi = formData.misi.filter(item => item && item.trim() !== '');
        const cleanTujuan = formData.tujuan.filter(item => item && item.trim() !== '');

        return {
            ...formData,
            misi: cleanMisi,
            tujuan: cleanTujuan.length > 0 ? cleanTujuan : null, // Set null jika tujuan kosong (opsional)
        };
    };

    // Submit Form (menggunakan PUT)
    const submit = (e) => {
        e.preventDefault();
        
        const submittedData = cleanDataForSubmission(data);
        
        put(route('admin.kampus.visimisi.update'), {
            data: submittedData,
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: `Data Visi, Misi, & Tujuan Kampus berhasil diperbarui.`,
                    confirmButtonColor: '#4F46E5',
                });
            },
            onError: (err) => {
                console.error("Error submitting form:", err);
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: 'Terjadi kesalahan saat memperbarui data. Periksa kembali isian Anda.',
                    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={faPencil} className="mr-3 w-6 h-6" />
                            {headerText}
                        </h3>
                        <div className="flex space-x-3">
                            <Link
                                href={route('admin.kampus.visimisi.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 ? 'Memperbarui...' : 'Update'}
                            </button>
                        </div>
                    </div>

                    {/* ======================= BAGIAN 1: TITLE ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3 flex items-center">
                         <FontAwesomeIcon icon={faPencil} className="mr-2" />
                         Judul <span className="text-red-500">*</span>
                    </h4>
                    <div className="mb-8">
                        <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">Judul Dokumen Visi, Misi, & Tujuan</label>
                        <input
                            id="title"
                            type="text"
                            name="title"
                            value={data.title}
                            onChange={handleInputChange}
                            placeholder="Contoh: Visi dan Misi Periode 2024-2029"
                            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>

                    
                    {/* ======================= BAGIAN 2: VISI ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3 flex items-center">
                        <FontAwesomeIcon icon={faEye} className="mr-2" />
                        Visi Kampus <span className="text-red-500">*</span>
                    </h4>
                    <div className="mb-8">
                        <label htmlFor="visi" className="sr-only">Visi Kampus</label>
                        <textarea
                            id="visi"
                            name="visi"
                            rows="4"
                            value={data.visi}
                            onChange={handleInputChange}
                            placeholder="Masukkan Visi Kampus secara detail di sini..."
                            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.visi ? 'border-red-500' : ''}`}
                        />
                        {errors.visi && <div className="text-xs text-red-600 mt-1">{errors.visi}</div>}
                    </div>


                    {/* ======================= BAGIAN 3: MISI ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-indigo-500 pl-3 flex items-center">
                        <FontAwesomeIcon icon={faBullseye} className="mr-2" />
                        Daftar Misi Kampus <span className="text-red-500">*</span>
                    </h4>
                    <p className="text-sm text-gray-500 mb-4">Sebutkan poin-poin Misi Kampus. Minimal satu poin wajib diisi.</p>
                    
                    {data.misi.map((misiItem, index) => (
                        <ArrayTextInput
                            key={`misi-${index}`}
                            index={index}
                            value={misiItem}
                            placeholder="Misi"
                            onChange={(i, v) => handleArrayChange('misi', i, v)}
                            onRemove={(i) => handleRemoveArrayItem('misi', i)}
                            errors={errors}
                            errorPrefix="misi"
                        />
                    ))}

                    <button
                        type="button"
                        onClick={() => handleAddArrayItem('misi')}
                        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 Misi
                    </button>
                    {errors.misi && <div className="text-xs text-red-600 mt-1 mb-8">{errors.misi}</div>}


                    {/* ======================= BAGIAN 4: TUJUAN (OPSIONAL) ======================= */}
                    <h4 className="text-lg font-semibold text-gray-700 mb-4 border-l-4 border-orange-500 pl-3 flex items-center">
                        <FontAwesomeIcon icon={faCrosshairs} className="mr-2" />
                        Daftar Tujuan Kampus <span className="text-gray-400 text-sm">(Opsional)</span>
                    </h4>
                    <p className="text-sm text-gray-500 mb-4">Sebutkan poin-poin Tujuan Kampus (dapat dikosongkan).</p>
                    
                    {data.tujuan.map((tujuanItem, index) => (
                        <ArrayTextInput
                            key={`tujuan-${index}`}
                            index={index}
                            value={tujuanItem}
                            placeholder="Tujuan"
                            onChange={(i, v) => handleArrayChange('tujuan', i, v)}
                            onRemove={(i) => handleRemoveArrayItem('tujuan', i)}
                            errors={errors}
                            errorPrefix="tujuan"
                        />
                    ))}

                    <button
                        type="button"
                        onClick={() => handleAddArrayItem('tujuan')}
                        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 Tujuan
                    </button>
                    {errors.tujuan && <div className="text-xs text-red-600 mt-1 mb-8">{errors.tujuan}</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 ? 'Memperbarui...' : 'Update'}
                        </button>
                    </div>

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