/**
 * Form Builder - Main container component
 */

import { __ } from '@wordpress/i18n';
import { useState, useCallback, useEffect } from '@wordpress/element';
import FormCanvas from './FormCanvas';
import FieldPalette from './FieldPalette';
import FieldSettingsPanel from './FieldSettingsPanel';
import FormPreview from './FormPreview';
import './FormBuilder.css';

export default function FormBuilder({ formId, initialData = {} }) {
    const [fields, setFields] = useState(initialData.fields || []);
    const [selectedFieldId, setSelectedFieldId] = useState(null);
    const [saveStatus, setSaveStatus] = useState(null);

    const selectedField = fields.find(f => f.field_id === selectedFieldId) || null;

    // Load existing fields on mount
    useEffect(() => {
        if (formId && !initialData.fields) {
            loadFields();
        }
    }, [formId]);

    const loadFields = useCallback(() => {
        const params = new URLSearchParams({
            action: 'formipay_load_form_fields',
            post_id: formId,
            _wpnonce: window.formipayAdmin?.nonce || '',
        });

        fetch(`${window.formipayAdmin?.ajaxUrl || '/wp-admin/admin-ajax.php'}?${params}`)
            .then(response => response.json())
            .then(result => {
                if (result.success && result.data.fields) {
                    setFields(result.data.fields);
                }
            })
            .catch(error => {
                console.error('Load error:', error);
            });
    }, [formId]);

    const handleDrop = useCallback((newField) => {
        setFields([...fields, newField]);
        setSelectedFieldId(newField.field_id);
    }, [fields]);

    const handleSelectField = useCallback((fieldId) => {
        setSelectedFieldId(fieldId);
    }, []);

    const handleUpdateField = useCallback((fieldId, updates) => {
        setFields(fields.map(f => f.field_id === fieldId ? { ...f, ...updates } : f));
    }, [fields]);

    const handleMoveField = useCallback((newFields) => {
        setFields(newFields);
    }, []);

    const handleDeleteField = useCallback((fieldId) => {
        const newFields = fields.filter(f => f.field_id !== fieldId);
        setFields(newFields);
        if (selectedFieldId === fieldId) {
            setSelectedFieldId(null);
        }
    }, [fields, selectedFieldId]);

    const handleSave = useCallback(() => {
        setSaveStatus('saving');
        const formData = new FormData();
        formData.append('action', 'formipay_save_form_fields');
        formData.append('post_id', formId);
        formData.append('fields', JSON.stringify(fields));
        formData.append('_wpnonce', window.formipayAdmin?.nonce || '');

        fetch(window.formipayAdmin?.ajaxUrl || '/wp-admin/admin-ajax.php', {
            method: 'POST',
            credentials: 'same-origin',
            body: formData,
        })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                setSaveStatus('saved');
                setTimeout(() => setSaveStatus(null), 2000);
            } else {
                setSaveStatus('error');
                console.error('Failed to save form:', result.message);
            }
        })
        .catch(error => {
            setSaveStatus('error');
            console.error('Save error:', error);
        });
    }, [fields, formId]);

    return (
        <div className="formipay-form-builder">
            <div className="formipay-builder-toolbar">
                <h2>{ __('Form Builder', 'formipay') }</h2>
                <div className="formipay-builder-actions">
                    <button
                        type="button"
                        className="button button-secondary"
                        onClick={() => setFields([])}
                    >
                        { __('Clear All', 'formipay') }
                    </button>
                    <button
                        type="button"
                        className={`button button-primary ${saveStatus === 'saving' ? 'is-busy' : ''}`}
                        onClick={handleSave}
                        disabled={saveStatus === 'saving'}
                    >
                        { saveStatus === 'saved' ? __('Saved!', 'formipay') :
                          saveStatus === 'error' ? __('Failed', 'formipay') :
                          saveStatus === 'saving' ? __('Saving...', 'formipay') :
                          __('Save Form', 'formipay') }
                    </button>
                </div>
            </div>

            <div className="formipay-builder-content">
                <FieldPalette onDragStart={() => {}} />
                <FormCanvas
                    fields={fields}
                    selectedFieldId={selectedFieldId}
                    onDrop={handleDrop}
                    onSelectField={handleSelectField}
                    onUpdateField={handleUpdateField}
                    onMoveField={handleMoveField}
                    onDeleteField={handleDeleteField}
                />
                <FormPreview fields={fields} />
                <FieldSettingsPanel
                    field={selectedField}
                    open={!!selectedField}
                    onClose={() => setSelectedFieldId(null)}
                    onUpdate={handleUpdateField}
                />
            </div>
        </div>
    );
}
