import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import {Spinner, PanelBody, SelectControl} from '@wordpress/components';
import { useState, useEffect } from "react";
import ServerSideRender from '@wordpress/server-side-render';
import SettingsForm from "./settingsForm";

/**
 * @param {{template :string, config :object, lastChanged :number, UUID :`${string}-${string}-${string}-${string}-${string}`|undefined}} attributes
 * @param {function} setAttributes
 * @param {string} tagName
 * @param {string[]} allowedTemplates
 * @param {string} renderEndpoint
 * @param {string} title
 * @returns {JSX.Element}
 * @constructor
 */
export default function PlanadayBlock({ attributes, setAttributes, tagName, allowedTemplates, renderEndpoint, title } ) {
	const templates = [];
	for (const label in allowedTemplates) {
		templates.push({label: label, value: allowedTemplates[label]});
	}

    let BlockUUID = attributes.UUID ?? crypto.randomUUID();
    if (attributes.UUID === undefined || attributes.UUID === null) {
        setAttributes({UUID: BlockUUID});
    }
	let currentTemplate = attributes.template ?? templates[0]["value"];

	const [settings, setSettings] = useState([(<div><Spinner /> instellingen aan het laden</div>)]);
	const [optionsJson, setOptionsJson] = useState(null);

	useEffect(() => {
		setSettings([(<div><Spinner /> instellingen aan het laden</div>)]);
		fetch(
			renderEndpoint,
			{
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify(attributes)
			}
		).then(
			response => response.json()
		).then(
			json => {
				if (!json.hasOwnProperty("options")) {
					setSettings([(
						<div>
							<p>Sorry, iets is mis gegaan. Kan niet de instellingen tonen momenteel.</p>
						</div>
					)]);
					return;
				}
				setOptionsJson(json);
			}
		).catch(error => {
			console.warn(error);
		});
	}, [currentTemplate]);

	useEffect(() => {
		if (!optionsJson) return;
		setSettings([ (<SettingsForm attributes={attributes} uuid={BlockUUID} setAttributes={ setAttributes } options={ optionsJson?.options}> </SettingsForm>)]);
	}, [optionsJson, attributes]);

	return (
		<>
			<InspectorControls>
				<PanelBody title='Template'>
					<SelectControl
						label='Template'
						value={ currentTemplate }
						options={ templates }
						onChange={ ( value ) =>
							setAttributes( { template: value } )
						}
					/>
				</PanelBody>
				{ settings }
			</InspectorControls>
			<div { ...useBlockProps() }>
				<ServerSideRender block={tagName} attributes={attributes} />
			</div>
		</>
	);
}