import * as React from 'react';
import { __ } from '@wordpress/i18n';

import { BlockEditProps } from '@wordpress/blocks';
import {
	Placeholder,
	ToolbarButton,
	RadioControl,
	PanelBody,
	PanelRow,
	ExternalLink,
} from '@wordpress/components';
import { edit } from '@wordpress/icons';

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

import { ReactComponent as CogIcon } from '@/assets/cogicon.svg';
import SelectDialog from '@/components/select-dialog';
import PreviewForm from '@/components/preview-form';
import { BlockAttributes, EmbedMode } from '@/types';

const Edit: React.FC<BlockEditProps<BlockAttributes>> = ( { attributes, setAttributes, className } ) => {
	const handleForm = ( form: { [key: string]: any } ) => {
		setAttributes( {
			formId: form.formId,
			seamlessEmbedCode: form.embedCodes.Seamless,
			iframeEmbedCode: form.embedCodes.IFrame,
			ampEmbedCode: form.embedCodes.Amp,
			embedMode: EmbedMode.Seamless,
		} );
	};

	const resetForm = () => {
		// Create a new object which sets all attributes to null
		const nullAttributes = Object.keys( attributes ).reduce(
			( accumulator, current ) => {
				// @ts-ignore
				accumulator[ current ] = null;
				return accumulator;
			}, {} );

		setAttributes( nullAttributes );
	};

	if ( ! attributes.formId ) {
		return (
			<div>
				<Placeholder
					icon={ CogIcon }
					label="Cognito Forms"
					className={ className }
					instructions={ __(
						'Click the button below to choose a form to embed.'
					) }
				>
					<SelectDialog onSelectForm={ handleForm }></SelectDialog>
				</Placeholder>
			</div>
		);
	}

	return (
		<div>
			{
				<BlockControls>
					<ToolbarButton
						icon={ edit }
						label="Edit"
						onClick={ () => resetForm() }
					/>
				</BlockControls>
			}

			<InspectorControls key="setting">
				<PanelBody title="Embed Settings">
					<PanelRow>
						<RadioControl
							label="Embed Mode"
							help={
								<span>
									The type of embed code to use with your form. <ExternalLink href="https://www.cognitoforms.com/support/10/style-publish">Learn more</ExternalLink>
								</span>
							}
							selected={ attributes.embedMode }
							options={ [
								{ label: 'Seamless', value: EmbedMode.Seamless },
								{ label: 'Iframe', value: EmbedMode.IFrame },
							] }
							onChange={ ( value: EmbedMode ) => setAttributes( { embedMode: parseInt( value.toString() ) } ) }
						/>
					</PanelRow>
				</PanelBody>
			</InspectorControls>

			<PreviewForm
				embedCode={ attributes.iframeEmbedCode }
			/>
		</div>
	);
};

export default Edit;
