import * as React from '@wordpress/element';
import { createHigherOrderComponent } from '@wordpress/compose';
import {
	BlockControls,
	store as blockEditorStore,
} from '@wordpress/block-editor';
import {
	Toolbar,
	ToolbarGroup,
	ToolbarButton,
	Dashicon,
} from '@wordpress/components';
import {
	useCurrentView,
	useEditEntryBlock,
	useEntriesBlock,
	useViewEntryBlock,
} from '../../hooks';
import { __ } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';

const ViewSelectorToolbar = createHigherOrderComponent( ( BlockEdit ) => {
	return ( props: any ) => {
		const currentView = useCurrentView();
		const entriesBlock = useEntriesBlock();
		const viewEntryBlock = useViewEntryBlock();
		const editEntryBlock = useEditEntryBlock();
		const { selectBlock } = useDispatch( blockEditorStore );

		if ( ! currentView || entriesBlock.attributes.mode !== 'multi-entry' ) {
			return <BlockEdit { ...props } />;
		}

		const toolbarButtons = [
			<ToolbarButton
				key="view-button-entries"
				icon={ <Dashicon icon="index-card" /> }
				label={ __( 'Switch to Entries View', 'gp-entry-blocks' ) }
				isActive={ currentView === 'entries' }
				onClick={ () => selectBlock( entriesBlock.clientId ) }
			/>,
		];

		if ( viewEntryBlock ) {
			toolbarButtons.push(
				<ToolbarButton
					key="view-button-view"
					icon={ <Dashicon icon="media-default" /> }
					label={ __( 'Switch to Single Entry View', 'gp-entry-blocks' ) }
					isActive={ currentView === 'view' }
					onClick={ () => selectBlock( viewEntryBlock.clientId ) }
				/>
			);
		}

		if ( editEntryBlock ) {
			toolbarButtons.push(
				<ToolbarButton
					key="view-button-edit"
					icon={ <Dashicon icon="welcome-write-blog" /> }
					label={ __( 'Switch to Edit Entry View', 'gp-entry-blocks' ) }
					isActive={ currentView === 'edit' }
					onClick={ () => selectBlock( editEntryBlock.clientId ) }
				/>
			);
		}

		/*
		 * It pains me to add this logic, but without it, the margin of the first button is not correct.
		 *
		 * If a group is used, it look fine with one button, but if any more buttons are added to the group, the first
		 * button does not have enough padding/margin on the left side.
		 */
		const ToolbarButtonWrapper =
			toolbarButtons.length === 1 ? ToolbarGroup : React.Fragment;

		return (
			<React.Fragment>
				<BlockEdit { ...props } />
				<BlockControls>
					<Toolbar>
						<ToolbarButtonWrapper>
							{ toolbarButtons }
						</ToolbarButtonWrapper>
					</Toolbar>
				</BlockControls>
			</React.Fragment>
		);
	};
}, 'withInspectorControl' );

export default ViewSelectorToolbar;
