// resources/js/Hooks/useSejarahForm.js

import { useForm } from '@inertiajs/react';
import { useState, useEffect } from 'react';

/**
 * Custom Hook untuk mengelola state form dan logic handler untuk halaman Edit Sejarah.
 * @param {object} history - Data sejarah dari props.
 * @returns {object} - Objek yang berisi data, handler, state, dll.
 */
export const useSejarahForm = (history, existingErrors) => {
    // 1. Logic Parse initialContentDetails (Dipindahkan dari SejarahEdit)
    let initialContentDetails;
    try {
        initialContentDetails = typeof history.content_details === 'string'
            ? JSON.parse(history.content_details)
            : history.content_details;
    } catch (e) {
        console.error("Gagal parse content_details:", e);
        initialContentDetails = { milestones: [{ year: '', title: '' }], extraParagraphs: [''] };
    }

    // 2. Inisialisasi useForm
    const { data, setData, post, processing, recentlySuccessful, errors: formErrors } = useForm({
        _method: 'put',
        title: history.title || '',
        subtitle: history.subtitle || '',
        image_file: null,
        existing_image_url: history.image_url_public || null,
        pull_quote: history.pull_quote || '',
        paragraphs: history.paragraphs && history.paragraphs.length > 0
            ? history.paragraphs
            : [''],
        content_details: {
            milestones: initialContentDetails.milestones && initialContentDetails.milestones.length > 0
                ? initialContentDetails.milestones
                : [{ year: '', title: '' }],
            extraParagraphs: initialContentDetails.extraParagraphs && initialContentDetails.extraParagraphs.length > 0
                ? initialContentDetails.extraParagraphs
                : [''],
        }
    });

    // State untuk menyimpan URL pratinjau gambar yang baru dipilih
    const [newImagePreview, setNewImagePreview] = useState(null);

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

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

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        setData('image_file', file || null);
    };

    const handleRemoveImage = (isNewImage = false) => {
        if (isNewImage) {
            setData('image_file', null);
            setNewImagePreview(null);
            document.getElementById('image_file').value = null;
        } else {
            setData('existing_image_url', null);
        }
    };

    // Handler untuk Paragraphs Utama
    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 {
            setData('paragraphs', ['']);
        }
    };

    // Handler untuk Milestones
    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
    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
    const currentImageUrl = newImagePreview || data.existing_image_url;


    return {
        data,
        setData,
        post,
        processing,
        recentlySuccessful,
        errors: { ...formErrors, ...existingErrors }, // Gabungkan error Inertia dan props
        handleInputChange,
        handleImageChange,
        handleRemoveImage,
        handleParagraphChange,
        handleAddParagraph,
        handleRemoveParagraph,
        handleMilestoneChange,
        handleAddMilestone,
        handleRemoveMilestone,
        handleExtraParagraphChange,
        handleAddExtraParagraph,
        handleRemoveExtraParagraph,
        currentImageUrl,
    };
};