import { useState, useEffect, useRef, useLayoutEffect } from "react";
import {Spinner} from '@wordpress/components';


export default function SettingsForm({options, uuid, setAttributes, attributes}) {
    const [displayDiv, setDisplayDiv] = useState(document.createElement("div"));
    const [spinner, setSpinner] = useState(<Spinner/>);
    const formRef = useRef(null);

    useLayoutEffect(() => {
        if (formRef.current !== null) formRef.current.appendChild(displayDiv);
    }, [formRef]);

    useEffect(() => {
        if (options === null || options === undefined) return;
        let formBuilder;
        import("../../../../Html/JSModules/build/FormBuilder/FormBuilder.js").then(({default: FormBuilder}) => {
            displayDiv.innerHTML = "";
            let config = attributes.config ?? {};
            formBuilder = new FormBuilder(options);
            formBuilder
                .loadData( config )
                .placeHtml(displayDiv)
                .runValidate();

            formBuilder.onValidChange.add((event) => {
                    if (event.isValid) {
                        wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'pad-block-' + uuid );
                        wp.data.dispatch( 'core/notices' ).removeNotice( 'pad-block-' + uuid );
                    } else {
                        wp.data.dispatch( 'core/editor' ).lockPostSaving( 'pad-block-' + uuid );
                        wp.data.dispatch( 'core/notices' ).createNotice(
                            'error',
                            'Please check the Planaday Blocks for errors in the settings',
                            { id: 'pad-block-' + uuid, isDismissible: false }
                        );
                    }
                });
            formBuilder.onChange.add(() => setAttributes({config: formBuilder.getData(false)}));

            setSpinner(<></>);
            if (formRef.current !== null) formRef.current.appendChild(displayDiv);
        });

        return () => {
            if (formBuilder !== undefined) {
                formBuilder.runValidate();
                formBuilder.clean();
            }
        }
    }, [options, displayDiv]);

    return (
        <>
            <div ref={formRef} className="planaday">
                {spinner}
            </div>
        </>
    );
}