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,
	SelectControl,
	TextControl,
	RangeControl
} from '@wordpress/components';

import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import ShapeDivider from '../components/shape-dividers/ShapeDivider';

import { DeviceContext } from '../components/responsive/deviceContext';
import DeviceControl from '../components/responsive/DeviceControl';
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 FLEX_OPTIONS = [
	{ label: 'Row', value: 'row' },
	{ label: 'Column', value: 'column' },
	{ label: 'Row Reverse', value: 'row-reverse' },
	{ label: 'Column Reverse', value: 'column-reverse' }
];

const WRAP_OPTIONS = [
	{ label: 'Wrap', value: 'wrap' },
	{ label: 'No Wrap', value: 'nowrap' }
];

const JUSTIFY_OPTIONS = [
	{ label: 'Start', value: 'flex-start' },
	{ label: 'Center', value: 'center' },
	{ label: 'End', value: 'flex-end' },
	{ label: 'Space Around', value: 'space-around' },
	{ label: 'Space Between', value: 'space-between' },
	{ label: 'Space Evenly', value: 'space-evenly' }
];

const ALIGN_OPTIONS = [
	{ label: 'Start', value: 'flex-start' },
	{ label: 'Center', value: 'center' },
	{ label: 'End', value: 'flex-end' },
	{ label: 'Space Around', value: 'space-around' },
	{ label: 'Space Between', value: 'space-between' },
	{ label: 'Space Evenly', value: 'space-evenly' }
];

const ALIGN_CONTENT_OPTIONS = [
	{ label: 'Start', value: 'flex-start' },
	{ label: 'Center', value: 'center' },
	{ label: 'End', value: 'flex-end' },
	{ label: 'Space Around', value: 'space-around' },
	{ label: 'Space Between', value: 'space-between' },
	{ label: 'Space Evenly', value: 'space-evenly' }
];

const Edit = ({ attributes, setAttributes, context, clientId }) => {
	const {
		id,
		contentWidth,
		ariaLabel = '',
		containerClass = '',
		htmlTag = 'section',
		flexWidth,
		flexDirection,
		flexWrap,
		justifyContent,
		alignItems,
		alignContent,
		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 handleResponsiveChange = (key) => (val) => {
		setAttributes({ [key]: val });
	};

	const getSectionContainerClasses = (attributes) => {
		const classes = ['container'];

		const contentWidth = attributes.contentWidth || 'md';
		const customContainerClass = attributes.containerClass || '';

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

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

		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');
	const isWrap = flexWrap?.[currentDevice] === 'wrap';

	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>
							: null}
						<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')}
							/>
							: null}
						<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' },
								{ label: '<nav>', value: 'nav' },
							]}
							onChange={(val) => setAttributes({ htmlTag: val })}
						/>
						{isNested && (
							<DeviceControl
								value={flexWidth}
								onChange={handleResponsiveChange('flexWidth')}
							>
								<RangeControl
									label={__('Width (%)', 'lead-gen')}
									min={0}
									max={100}
									step={1}
								/>
							</DeviceControl>
						)}
						<DeviceControl
							value={flexDirection}
							onChange={handleResponsiveChange('flexDirection')}
						>
							<SelectControl
								label={__('Direction', 'lead-gen')}
								options={FLEX_OPTIONS}
							/>
						</DeviceControl>
						<DeviceControl
							value={flexWrap}
							onChange={handleResponsiveChange('flexWrap')}
						>
							<SelectControl
								label={__('Wrap', 'lead-gen')}
								options={WRAP_OPTIONS}
							/>
						</DeviceControl>
						<DeviceControl
							value={justifyContent}
							onChange={handleResponsiveChange('justifyContent')}
						>
							<SelectControl
								label={__('Justify Content', 'lead-gen')}
								options={JUSTIFY_OPTIONS}
							/>
						</DeviceControl>
						<DeviceControl
							value={alignItems}
							onChange={handleResponsiveChange('alignItems')}
						>
							<SelectControl
								label={__('Align Items', 'lead-gen')}
								options={ALIGN_OPTIONS}
							/>
						</DeviceControl>
						{isWrap && (
							<DeviceControl
								value={alignContent}
								onChange={handleResponsiveChange('alignContent')}
							>
								<SelectControl
									label={__('Align Content', 'lead-gen')}
									options={ALIGN_CONTENT_OPTIONS}
								/>
							</DeviceControl>
						)}
					</PanelBody>
					<BackgroundControls attributes={attributes} setAttributes={setAttributes} />
					<ShapeDividerControls attributes={attributes} setAttributes={setAttributes} />
					<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
					<AnimationControls attributes={attributes} setAttributes={setAttributes} />
				</InspectorControls>

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

						{/* Background Video */}
						{(backgroundVideo && backgroundVideoData) && (
							<video
								className="section__overlay-video"
								autoPlay
								muted
								loop
								playsInline
								preload="auto"
							>
								<source src={backgroundVideoData.source_url} type={backgroundVideoData.mime_type} />
								Your browser does not support the video tag.
							</video>
						)}

						{/* Background Overlay Color */}
						{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 />
					</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;
