import { useEffect, useState } from '@wordpress/element';
import { InnerBlocks, InspectorControls } from '@wordpress/block-editor';
import AnimationControls from '../components/animations/AnimationControl';
import AnimatedBlockWrapper from '../components/animations/AnimatedBlockWrapper';
import { DeviceContext } from '../components/responsive/deviceContext';
import VisibilityControls from '../components/visibility/VisibilityControls';
import LegacyFlexAlignmentControls from '../components/alignment/LegacyFlexAlignmentControls';
import {getVisibilityClasses} from "../components/blockStyleUtils";

const DEVICE_MAP = {
	xs: 'mobile',
	sm: 'tablet',
	md: 'large-tablet',
	lg: 'laptop',
	xl: 'desktop',
};

export const getRowUtilityClasses = (attributes) => {
	const classes = [];

	for (const [key, device] of Object.entries(DEVICE_MAP)) {
		const justify = attributes.horizontalAlign?.[device];
		const align = attributes.verticalAlign?.[device];

		if (justify) {
			classes.push(`${justify}-${key}`);
		}
		if (align) {
			classes.push(`${align}-${key}`);
		}
	}

	const visibilityClasses = getVisibilityClasses(attributes);
	if (visibilityClasses) {
		classes.push(visibilityClasses);
	}

	return classes.join(' ');
};

const Edit = ({ attributes, setAttributes, clientId }) => {
	const {
		id,
		animationEntrance,
		animationDuration,
		animationDelay,
	} = attributes;

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

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

	return (
		<DeviceContext.Provider value={[currentDevice, setCurrentDevice]}>
			<AnimatedBlockWrapper
				animationEntrance={animationEntrance}
				animationDuration={animationDuration}
				animationDelay={animationDelay}
				attributes={attributes}
				className={`lg-block__row row ${getRowUtilityClasses(attributes)}`}
			>
				<InspectorControls>
					<LegacyFlexAlignmentControls attributes={attributes} setAttributes={setAttributes} />
					<VisibilityControls attributes={attributes} setAttributes={setAttributes} />
					<AnimationControls attributes={attributes} setAttributes={setAttributes} />
				</InspectorControls>
				<InnerBlocks
					allowedBlocks={['leadgen/column']}
					template={[['leadgen/column', {}]]}
					orientation="horizontal"
				/>
			</AnimatedBlockWrapper>
		</DeviceContext.Provider>
	);
};

export default Edit;
