import React from 'react';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { Placeholder, PanelBody, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import FilterFieldsControl from './FilterFieldsControl';
import BlockPreview from '../../components/BlockPreview';

import {
	arrowRight,
	arrowDown,
} from '@wordpress/icons';

export interface FiltersAttributes {
	filters: any[];
	orientation: 'horizontal' | 'vertical'
}

const Edit = ( args: BlockProps< FiltersAttributes > ) => {
	const blockProps = useBlockProps( {
		className: args.attributes?.orientation === 'vertical' ? 'is-orientation-vertical' : 'is-orientation-horizontal',
	} );

	return (
		<div { ...blockProps }>
			<InspectorControls>
				{ args.context[ 'gp-entry-blocks/formId' ] && (
					<>
						<PanelBody
							className="gpeb_panel_filters_settings"
							title={ __( 'Settings', 'gp-entry-blocks' ) }
						>
							<FilterFieldsControl
								{ ...args }
								label={ __( 'Filters', 'gp-entry-blocks' ) }
							/>

							<fieldset className="block-editor-hooks__flex-layout-orientation-controls">
								<legend>{ __( 'Orientation' ) }</legend>
								<Button
									label={ 'horizontal' }
									icon={ arrowRight }
									isPressed={ args.attributes.orientation === 'horizontal' }
									onClick={ () =>
										args.setAttributes( {
											orientation: 'horizontal',
										} )
									}
								/>
								<Button
									label={ 'vertical' }
									icon={ arrowDown }
									isPressed={ args.attributes.orientation === 'vertical' }
									onClick={ () =>
										args.setAttributes( {
											orientation: 'vertical',
										} )
									}
								/>
							</fieldset>
						</PanelBody>
					</>
				) }
			</InspectorControls>

			{
				args.attributes?.filters?.length ? <BlockPreview { ...args } /> : <Placeholder
					label={ __( 'Filters', 'gp-entry-blocks' ) }
					instructions={ __(
						'Please select fields that you wish to be filterable.',
						'gp-entry-blocks'
					) }
				/>
			}
		</div>
	);
};

/**
 * Blocks with dynamic PHP backends require that we only serialize the attributes.
 *
 * @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/
 */
const Save = () => {
	return null;
};

export const settings = {
	edit: Edit,
	save: Save,
};
