/**
 * 360° Panorama Tour block.
 */
import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import {
	SelectControl,
	RangeControl,
	PanelBody,
	Placeholder,
} from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { decodeEntities } from '@wordpress/html-entities';

import metadata from '../block.json';

const Edit = ( { attributes, setAttributes } ) => {
	const { tourId, height } = attributes;
	const blockProps = useBlockProps();

	const tours = useSelect(
		( select ) =>
			select( coreStore ).getEntityRecords( 'postType', 'vist360_tour', {
				per_page: 100,
			} ),
		[]
	);

	const options = [
		{
			value: 0,
			label: __(
				'— Select a tour —',
				'vistour-virtual-tour-builder'
			),
		},
		...( tours || [] ).map( ( tour ) => ( {
			value: tour.id,
			label:
				decodeEntities( tour.title.rendered ) ||
				__( '(no title)', 'vistour-virtual-tour-builder' ),
		} ) ),
	];

	const selected = ( tours || [] ).find( ( tour ) => tour.id === tourId );

	return (
		<div { ...blockProps }>
			<InspectorControls>
				<PanelBody
					title={ __( 'Tour', 'vistour-virtual-tour-builder' ) }
				>
					<SelectControl
						__nextHasNoMarginBottom
						label={ __(
							'Tour',
							'vistour-virtual-tour-builder'
						) }
						value={ tourId }
						options={ options }
						onChange={ ( value ) =>
							setAttributes( { tourId: parseInt( value, 10 ) } )
						}
					/>
					<RangeControl
						__nextHasNoMarginBottom
						label={ __(
							'Height (px, 0 = tour default)',
							'vistour-virtual-tour-builder'
						) }
						min={ 0 }
						max={ 1200 }
						step={ 10 }
						value={ height }
						onChange={ ( value ) =>
							setAttributes( { height: value } )
						}
					/>
				</PanelBody>
			</InspectorControls>

			<Placeholder
				icon="format-image"
				label={ __(
					'360° Panorama Tour',
					'vistour-virtual-tour-builder'
				) }
				instructions={
					selected
						? decodeEntities( selected.title.rendered )
						: __(
								'Select a tour in the block settings sidebar.',
								'vistour-virtual-tour-builder'
						  )
				}
			>
				{ ! tours &&
					__( 'Loading tours…', 'vistour-virtual-tour-builder' ) }
			</Placeholder>
		</div>
	);
};

registerBlockType( metadata.name, {
	edit: Edit,
	save: () => null,
} );
