/**
 * WordPress dependencies
 */
import ServerSideRender from '@wordpress/server-side-render';

import {
	Disabled,
	PanelBody,
	PanelRow,
	RangeControl,
	SelectControl,
	TextControl,
	TextareaControl,
	ToggleControl
} from '@wordpress/components';

import { InspectorControls,	PanelColorSettings,	useBlockProps } from '@wordpress/block-editor';

import { useEffect,	useMemo, useRef } from '@wordpress/element';

import { applyFilters } from '@wordpress/hooks';

import { useSelect } from '@wordpress/data';

/**
 * Internal dependencies
 */
import { BuildTree,	GroupByParent } from '../utils';

/**
 * Describes the structure of the block in the context of the editor.
 * This represents what the editor will render when the block is used.
 *
 * @return {WPElement} Element to render.
 */
function Edit( { attributes, setAttributes } ) {	

	const podcasts = aiopod_blocks.podcasts;	

	const categoryItems = useSelect( ( select ) => {
		return select( 'core' ).getEntityRecords( 'taxonomy', 'aiopod_categories', {
			'per_page': -1
		});
	});

	const participantItems = useSelect( ( select ) => {
		return select( 'core' ).getEntityRecords( 'taxonomy', 'aiopod_participants', {
			'per_page': -1
		});	
	});

	const categoryList = useMemo( () => {
		let options = [];

		if ( categoryItems && categoryItems.length > 0 ) {		
			let grouped = GroupByParent( categoryItems );
			let tree    = BuildTree( grouped );
			
			options = [ ...options, ...tree ];
		}

		return options;
	}, [ categoryItems ] );

	const participantList = useMemo( () => {
		let options = [];

		if ( participantItems && participantItems.length > 0 ) {
			for ( let i = 0; i < participantItems.length; i += 1 ) {
				options.push({
					label: participantItems[ i ].name,
					value: participantItems[ i ].id,
				});
			}
		}

		return options;
	}, [ participantItems ] );

	const getControl = ( field, index ) => {
		if ( ! canShowControl( field.name ) ) {
			return '';
		}

		const placeholder = field.placeholder ? field.placeholder : '';
		const description = field.description ? field.description : '';

		switch ( field.type ) {
			case 'header':
				return <PanelRow key={ index }>
						<h3 className="aiopod-no-margin">{ field.label }</h3>
					</PanelRow>	
			case 'categories':
				return <PanelRow key={ index } className="aiopod-block-multiselect">
					<SelectControl
						multiple
						label={ field.label }
						help={ description }						
						options={ categoryList }
						value={ attributes[ field.name ] }
						onChange={ onChange( field.name ) }
            			__nextHasNoMarginBottom={ true }
            			__next40pxDefaultSize={ true }
					/>
				</PanelRow>
			case 'participants':
				return <PanelRow key={ index } className="aiopod-block-multiselect">
					<SelectControl
						multiple
						label={ field.label }
						help={ description }						
						options={ participantList }
						value={ attributes[ field.name ] }
						onChange={ onChange( field.name ) }
            			__nextHasNoMarginBottom={ true }
            			__next40pxDefaultSize={ true }
					/>
				</PanelRow>		
			case 'number':
				return <PanelRow key={ index }>
					<RangeControl	
						label={ field.label }
						help={ description }
						placeholder={ placeholder }
						value={ attributes[ field.name ] }
						min={ field.min }
						max={ field.max }
						onChange={ onChange( field.name ) }
            			__nextHasNoMarginBottom={ true }
            			__next40pxDefaultSize={ true }
					/>
				</PanelRow>
			case 'textarea':
				return <PanelRow key={ index }>
					<TextareaControl
						label={ field.label }
						help={ description }
						placeholder={ placeholder }
						value={ attributes[ field.name ] }
						onChange={ onChange( field.name ) }
						__nextHasNoMarginBottom={ true }
					/>
				</PanelRow>
			case 'select':
			case 'radio':
				let options = [];

				for ( let key in field.options ) {
					options.push({
						label: field.options[ key ],
						value: key
					});
				};

				return <PanelRow key={ index }>
					<SelectControl
						label={ field.label }
						help={ description }						
						options={ options }
						value={ attributes[ field.name ] }
						onChange={ onChange( field.name ) }
            			__nextHasNoMarginBottom={ true }
            			__next40pxDefaultSize={ true }
					/>
				</PanelRow>
			case 'checkbox':
				return <PanelRow key={ index }>
					<ToggleControl
						label={ field.label }
						help={ description }
						checked={ attributes[ field.name ] }
						onChange={ toggleAttribute( field.name ) }
						__nextHasNoMarginBottom={ true }
					/>
				</PanelRow>
			case 'color':
				return <PanelRow key={ index }>
					<PanelColorSettings						
						title={ field.label }
						colorSettings={ [
							{
								label: aiopod_blocks.i18n.select_color,
								value: attributes[ field.name ],
								onChange: onChange( field.name )					
							}
						] }
					>							
					</PanelColorSettings>
				</PanelRow>
			default:
				return <PanelRow key={ index }>
					<TextControl	
						label={ field.label }
						help={ description }
						placeholder={ placeholder }
						value={ attributes[ field.name ] }
						onChange={ onChange( field.name ) }
            			__nextHasNoMarginBottom={ true }
            			__next40pxDefaultSize={ true }
					/>
				</PanelRow>
		}		
	}

	const canShowPanel = ( panel ) => {
		return applyFilters( 'aiopod_block_toggle_panels', true, panel, attributes );
	}

	const canShowControl = ( control ) => {
		return applyFilters( 'aiopod_block_toggle_controls', true, control, attributes );
	}

	const onChange = ( attribute ) => {
		return ( newValue ) => {
			setAttributes( { [ attribute ]: newValue } );		
		};
	}

	const toggleAttribute = ( attribute ) => {
		return ( newValue ) => {
			setAttributes( { [ attribute ]: newValue } );
		};
	}	

	const mounted = useRef();	
	useEffect( () => {
		if ( ! mounted.current ) {
			// Do componentDidMount logic
			mounted.current = true;
		} else {
			// Do componentDidUpdate logic
			applyFilters( 'aiopod_block_init', attributes );
		}
	} );

	return (
		<>
			<InspectorControls>
				{Object.keys( podcasts ).map(( key, index ) => {
					return (
						canShowPanel( key ) && <PanelBody 
							key={ 'aiopod-block-panel-' + index } 
							title={ podcasts[ key ].title }
							initialOpen={ 0 == index ? true : false }
							className="aiopod-block-panel">
								
							{Object.keys( podcasts[ key ].fields ).map(( _key, _index ) => {
								return getControl( podcasts[ key ].fields[ _key ], 'aiopod-block-control-' + _index );
							})}

						</PanelBody>
					)
				})}
			</InspectorControls>

			<div { ...useBlockProps() }>
				<Disabled>
					<ServerSideRender
						block="aiopod/podcasts"
						attributes={ attributes }
					/>
				</Disabled>
			</div>
		</>
	);
}

export default Edit;