/**
 * GoValid Form Gutenberg block.
 *
 * @package GoValid_QR
 */

/* global wp */
(function () {
	'use strict';

	var el            = wp.element.createElement;
	var registerBlock = wp.blocks.registerBlockType;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var PanelBody     = wp.components.PanelBody;
	var TextControl   = wp.components.TextControl;
	var useEffect     = wp.element.useEffect;
	var useState      = wp.element.useState;
	var __             = wp.i18n.__;

	registerBlock('govalid-qr/form', {
		edit: function (props) {
			var formId    = props.attributes.formId;
			var formTitle = props.attributes.formTitle;
			var setAttributes = props.setAttributes;

			var _state   = useState([]);
			var forms    = _state[0];
			var setForms = _state[1];

			// Load forms list on mount.
			useEffect(function () {
				wp.apiFetch({ path: 'govalid-qr/v1/forms?per_page=100' }).then(function (data) {
					setForms(data.items || []);
				});
			}, []);

			var selectedForm = null;
			forms.forEach(function (f) {
				if (parseInt(f.id, 10) === formId) selectedForm = f;
			});

			return el('div', { className: 'govalid-form-block-editor' },
				el(InspectorControls, null,
					el(PanelBody, { title: __('Form Settings', 'govalid-qr') },
						el(TextControl, {
							label: __('Form ID', 'govalid-qr'),
							value: formId || '',
							type: 'number',
							onChange: function (val) {
								var id = parseInt(val, 10) || 0;
								setAttributes({ formId: id });
								// Find title.
								forms.forEach(function (f) {
									if (parseInt(f.id, 10) === id) {
										setAttributes({ formTitle: f.title });
									}
								});
							}
						})
					)
				),
				// Block preview.
				formId
					? el('div', { className: 'govalid-form-block-preview' },
						el('span', { className: 'dashicons dashicons-forms', style: { fontSize: '24px', marginRight: '8px', color: '#2563eb' } }),
						el('span', null, (formTitle || __('GoValid Form', 'govalid-qr')) + ' (ID: ' + formId + ')')
					)
					: el('div', { className: 'govalid-form-block-placeholder' },
						el('span', { className: 'dashicons dashicons-forms', style: { fontSize: '32px', marginBottom: '8px', color: '#94a3b8' } }),
						el('p', null, __('Select a form in the block settings.', 'govalid-qr')),
						forms.length
							? el('div', { className: 'govalid-form-block-picker' },
								forms.map(function (f) {
									return el('button', {
										key: f.id,
										className: 'button',
										onClick: function () {
											setAttributes({ formId: parseInt(f.id, 10), formTitle: f.title });
										}
									}, f.title || __('Untitled', 'govalid-qr'));
								})
							)
							: null
					)
			);
		},

		save: function () {
			// Server-side rendered.
			return null;
		}
	});
})();
