import { __ } from '@wordpress/i18n';
import { useEffect, useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import {
	InnerBlocks,
	InspectorControls
} from '@wordpress/block-editor';
import {
	__experimentalToggleGroupControl as ToggleGroupControl,
	__experimentalToggleGroupControlOption as ToggleGroupControlOption,
	PanelBody,
	TextControl,
	SelectControl
} from '@wordpress/components';

import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import ShapeDivider from '../components/shape-dividers/ShapeDivider';
import { DeviceContext } from '../components/responsive/deviceContext';
import AnimationControls from '../components/animations/AnimationControl';
import ShapeDividerControls from '../components/shape-dividers/ShapeDividerControls';
import BackgroundControls from '../components/background/BackgroundControls';
import VisibilityControls from "../components/visibility/VisibilityControls";
import {getVisibilityClasses} from "../components/blockStyleUtils";

const Edit = ({ attributes, setAttributes, context, clientId }) => {
	const {
		id,
		contentWidth,
		ariaLabel = '',
		containerClass = '',
		htmlTag = 'section',
		backgroundImage,
		backgroundVideo,
		placeholderDimensions,
		backgroundPosition,
		backgroundOverlay,
		backgroundOverlayColor,
		shapeDividerTop,
		shapeDividerBottom,
		animationEntrance = '',
		animationDuration = '',
		animationDelay = ''
	} = attributes;

	useEffect(() => {
		if (!id && clientId) {
			setAttributes({ id: clientId });
		}
	}, [id, clientId, setAttributes]);

	const isNested = context['core/block-editor/parentBlockId'] !== undefined;

	useEffect(() => {
		if (!contentWidth) {
			setAttributes({ contentWidth: isNested ? 'fluid' : 'md' });
		}
		setAttributes({ htmlTag: isNested ? 'div' : 'section' });
	}, [contentWidth, isNested, setAttributes]);
	const getSectionContainerClasses = (attrs) => {
		const classes = ['container'];
		const currentContentWidth = attrs.contentWidth || 'md';
		const customContainerClass = attrs.containerClass || '';

		if (currentContentWidth) {
			classes.push(`container-${currentContentWidth}`);
		}

		if (customContainerClass) {
			classes.push(customContainerClass);
		}

		if (attrs.verticalAlign) {
			classes.push(`items-${attrs.verticalAlign}`);
		}

		return classes.join(' ');
	};

	const backgroundImageData = useSelect(
		(select) => backgroundImage ? select('core').getMedia(backgroundImage) : null,
		[backgroundImage]
	);

	const backgroundVideoData = useSelect(
		(select) => backgroundVideo ? select('core').getMedia(backgroundVideo) : null,
		[backgroundVideo]
	);

	const [currentDevice, setCurrentDevice] = useState('desktop');

	return (
		<DeviceContext.Provider value={[currentDevice, setCurrentDevice]}>
			<AnimatedBlockWrapper
				animationEntrance={animationEntrance}
				animationDuration={animationDuration}
				animationDelay={animationDelay}
				attributes={attributes}
				className={`lg-block lg-block__section section ${getVisibilityClasses(attributes)}`}
				htmlTag={htmlTag}
			>
				<InspectorControls>
					<PanelBody title={__('Layout', 'lead-gen')}>
						{!isNested && (
							<ToggleGroupControl
								label="Content Width"
								value={contentWidth}
								isBlock
								__nextHasNoMarginBottom
								__next40pxDefaultSize
								onChange={(val) => setAttributes({ contentWidth: val })}
							>
								<ToggleGroupControlOption value="xs" label="XS" />
								<ToggleGroupControlOption value="sm" label="SM" />
								<ToggleGroupControlOption value="md" label="MD" />
								<ToggleGroupControlOption value="lg" label="LG" />
								<ToggleGroupControlOption value="xl" label="XL" />
								<ToggleGroupControlOption value="fluid" label="Full" />
							</ToggleGroupControl>
						)}

						<SelectControl
							label={__('HTML Tag', 'lead-gen')}
							value={htmlTag}
							options={[
								{ label: 'section', value: 'section' },
								{ label: 'div', value: 'div' },
								{ label: 'header', value: 'header' },
								{ label: 'footer', value: 'footer' },
								{ label: 'main', value: 'main' },
								{ label: 'article', value: 'article' },
								{ label: 'aside', value: 'aside' },
							]}
							onChange={(val) => setAttributes({ htmlTag: val })}
						/>

						<SelectControl
							label={__('Vertical Align', 'lead-gen')}
							value={attributes.verticalAlign}
							options={[
								{ label: __('None', 'lead-gen'), value: '' },
								{ label: __('Top', 'lead-gen'), value: 'top' },
								{ label: __('Middle', 'lead-gen'), value: 'middle' },
								{ label: __('Bottom', 'lead-gen'), value: 'bottom' },
							]}
							onChange={(val) => setAttributes({ verticalAlign: val })}
						/>

						<TextControl
							label={__('Aria Label', 'lead-gen')}
							value={ariaLabel}
							onChange={(val) => setAttributes({ ariaLabel: val })}
							placeholder={__('Optional accessibility label', 'lead-gen')}
						/>
						{!isNested && (
							<TextControl
								label={__('Custom Container Class', 'lead-gen')}
								value={containerClass}
								onChange={(val) => setAttributes({ containerClass: val })}
								placeholder={__('e.g. container--narrow', 'lead-gen')}
							/>
						)}
					</PanelBody>

					<BackgroundControls attributes={attributes} setAttributes={setAttributes} />
					<ShapeDividerControls attributes={attributes} setAttributes={setAttributes} />
					<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
					<AnimationControls attributes={attributes} setAttributes={setAttributes} />
				</InspectorControls>

				{(backgroundImage || placeholderDimensions?.width || backgroundVideo) && (
					<div className="section__overlay">
						{(backgroundImage && backgroundImageData) ? (
							<img
								className="section__overlay-img"
								src={backgroundImageData.source_url}
								alt={backgroundImageData.alt_text || 'Background image'}
								title={backgroundImageData.title?.rendered || 'Background image'}
								style={{
									objectPosition: `${(backgroundPosition?.x || 0.5) * 100}% ${(backgroundPosition?.y || 0.5) * 100}%`,
								}}
							/>
						) : placeholderDimensions?.width && placeholderDimensions?.height ? (
							<img
								className="section__overlay-img"
								src={`https://placehold.co/${placeholderDimensions.width}x${placeholderDimensions.height}`}
								alt="Placeholder - Please Replace Me"
								title="Placeholder - Please Replace Me"
							/>
						) : null}

						{(backgroundVideo && backgroundVideoData) && (
							<video
								className="section__overlay-video"
								autoPlay
								muted
								loop
								playsInline
								preload="auto"
								poster={backgroundImageData?.source_url || ''}
							>
								<source src={backgroundVideoData.source_url} type={backgroundVideoData.mime_type} />
								{__('Your browser does not support the video tag.', 'lead-gen')}
							</video>
						)}

						{backgroundOverlay && (
							<div
								className="section__overlay-color"
								style={{
									backgroundColor: backgroundOverlayColor || 'rgba(0, 0, 0, 0.5)',
								}}
								aria-hidden="true"
							/>
						)}
					</div>
				)}

				{shapeDividerTop?.type && shapeDividerTop.type !== 'none' && (
					<ShapeDivider
						type={shapeDividerTop.type}
						color={shapeDividerTop.color}
						height={shapeDividerTop.height}
						flip={shapeDividerTop.flip}
						position="top"
					/>
				)}

				{!isNested ?
					<div className={getSectionContainerClasses(attributes)}>
						<InnerBlocks
							allowedBlocks={['leadgen/row']}
							template={[
								['leadgen/row', {}]
							]}
							orientation="horizontal"
						/>
					</div>
					:
					<InnerBlocks
					/>
				}

				{shapeDividerBottom?.type && shapeDividerBottom.type !== 'none' && (
					<ShapeDivider
						type={shapeDividerBottom.type}
						color={shapeDividerBottom.color}
						height={shapeDividerBottom.height}
						flip={shapeDividerBottom.flip}
						position="bottom"
					/>
				)}
			</AnimatedBlockWrapper>
		</DeviceContext.Provider>
	);
};

export default Edit;
