import { __ } from '@wordpress/i18n';
import {
	BlockControls,
	InspectorControls,
	PlainText,
} from '@wordpress/block-editor';
import {
	ToolbarGroup,
	ToolbarButton,
	PanelBody,
	TextControl,
} from '@wordpress/components';
import { useState } from '@wordpress/element';
import ServerSideRender from '@wordpress/server-side-render';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ({ attributes, setAttributes, name }) => {
	const {
		shortcode = '',
		animationEntrance = '',
		animationDuration = '',
		animationDelay = '',
	} = attributes;

	const [showPreview, setShowPreview] = useState(true);

	return (
		<AnimatedBlockWrapper
			animationEntrance={animationEntrance}
			animationDuration={animationDuration}
			animationDelay={animationDelay}
			attributes={attributes}
			className={`lg-block lg-block__shortcode ${getVisibilityClasses(attributes)}`}
		>
			<BlockControls>
				<ToolbarGroup>
					<ToolbarButton
						icon="visibility"
						label={__('Toggle Preview', 'lead-gen')}
						isPressed={showPreview}
						onClick={() => setShowPreview((prev) => !prev)}
					/>
				</ToolbarGroup>
			</BlockControls>

			<InspectorControls>
				<PanelBody title={__('Shortcode Settings', 'lead-gen')} initialOpen={true}>
					<TextControl
						label={__('Shortcode', 'lead-gen')}
						value={shortcode}
						onChange={(value) => setAttributes({ shortcode: value })}
						help={__('Enter a valid WordPress shortcode, e.g. [gravityform id="1"]', 'lead-gen')}
					/>
				</PanelBody>
				<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
				<AnimationControls attributes={attributes} setAttributes={setAttributes} />
			</InspectorControls>

			{showPreview ?
				<ServerSideRender block={name} attributes={attributes} />
			:
				<PlainText
					value={shortcode}
					onChange={(value) => setAttributes({ shortcode: value })}
					placeholder={__('Enter a shortcode to preview it here.', 'lead-gen')}
					className="shortcode-edit-plain"
				/>
			}
		</AnimatedBlockWrapper>
	);
};

export default Edit;
