import { useState, useEffect, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import Select from 'react-select';
import { alignmentList, widthsList } from './helper';

import './styles/MediaControl.scss';

const MediaControls = ( { selectedElement, onUpdate, onClose, isOpen } ) => {
	const [ position, setPosition ] = useState( { top: 0, left: 0 } );
	const [ elementStyles, setElementStyles ] = useState( {
		width: '',
		height: '',
		float: '',
		textAlign: '',
		margin: '',
	} );
	const controlsRef = useRef( null );

	useEffect( () => {
		if ( selectedElement && isOpen ) {
			updatePosition();
			updateElementStyles();

			const handleScroll = () => updatePosition();
			const handleResize = () => updatePosition();
			const handleEditorScroll = () => updatePosition();

			window.addEventListener( 'scroll', handleScroll, {
				passive: true,
			} );
			window.addEventListener( 'resize', handleResize );
			document.addEventListener( 'scroll', handleEditorScroll, {
				capture: true,
				passive: true,
			} );

			return () => {
				window.removeEventListener( 'scroll', handleScroll );
				window.removeEventListener( 'resize', handleResize );
				document.removeEventListener( 'scroll', handleEditorScroll, {
					capture: true,
				} );
			};
		}
	}, [ selectedElement, isOpen ] );

	const updatePosition = () => {
		if ( ! selectedElement ) {
			return;
		}

		try {
			const rect = selectedElement.getBoundingClientRect();
			const scrollTop =
				window.pageYOffset || document.documentElement.scrollTop;
			const scrollLeft =
				window.pageXOffset || document.documentElement.scrollLeft;

			const top = rect.top + scrollTop - 55;
			const left = Math.max( rect.left + scrollLeft, 10 );

			const maxLeft = window.innerWidth - 400;

			setPosition( {
				top: Math.max( top, 10 ),
				left: Math.min( left, maxLeft ),
			} );
		} catch ( error ) {
			console.warn( 'Error updating media controls position:', error );
		}
	};

	const updateElementStyles = () => {
		if ( ! selectedElement ) {
			return;
		}

		try {
			const computedStyle = window.getComputedStyle( selectedElement );
			const parentElement = selectedElement.parentElement;
			const parentStyle = parentElement
				? window.getComputedStyle( parentElement )
				: null;

			setElementStyles( {
				width:
					selectedElement.style.width ||
					( computedStyle.width !== 'auto'
						? computedStyle.width
						: '' ),
				height: selectedElement.style.height || 'auto',
				float:
					selectedElement.style.float ||
					computedStyle.float ||
					'none',
				textAlign: parentStyle?.textAlign || 'left',
				margin: selectedElement.style.margin || '0',
			} );
		} catch ( error ) {
			console.warn( 'Error updating element styles:', error );
		}
	};

	const maintainSelectionAfterStyleChange = ( callback ) => {
		if ( ! selectedElement ) {
			return;
		}

		try {
			callback();

			setTimeout( () => {
				if ( selectedElement && selectedElement.parentNode ) {
					selectedElement.style.border =
						'2px solid var(--quizpress-primary)';
					selectedElement.style.outline = 'none';
					selectedElement.dataset.selected = 'true';

					updateElementStyles();
					updatePosition();

					onUpdate();
				}
			}, 10 );
		} catch ( error ) {
			console.warn(
				'Error maintaining selection after style change:',
				error
			);
		}
	};

	const handleWidthChange = ( newWidth ) => {
		maintainSelectionAfterStyleChange( () => {
			if ( newWidth === 'auto' ) {
				selectedElement.style.width = 'auto';
				selectedElement.style.height = 'auto';
			} else {
				selectedElement.style.width = newWidth;
				selectedElement.style.height = 'auto';
				selectedElement.style.maxWidth = '100%';
			}
		} );
	};

	const handlePositionChange = ( positionType ) => {
		maintainSelectionAfterStyleChange( () => {
			const parentElement = selectedElement.parentElement;

			selectedElement.style.float = 'none';
			selectedElement.style.margin = '0';
			selectedElement.style.display = '';
			if ( parentElement ) {
				parentElement.style.textAlign = '';
			}

			switch ( positionType ) {
				case 'left':
					selectedElement.style.float = 'left';
					selectedElement.style.margin = '0 0 0 0';
					break;
				case 'center':
					selectedElement.style.display = 'block';
					selectedElement.style.margin = '0 auto 0 auto';
					if ( parentElement ) {
						parentElement.style.textAlign = 'center';
					}
					break;
				case 'right':
					selectedElement.style.float = 'right';
					selectedElement.style.margin = '0 0 0 0';
					break;
				case 'none':
				default:
					break;
			}
		} );
	};

	const handleResize = ( direction ) => {
		maintainSelectionAfterStyleChange( () => {
			const currentWidth = parseInt( selectedElement.offsetWidth ) || 200;
			let newWidth = currentWidth;

			switch ( direction ) {
				case 'increase':
					newWidth = Math.min( currentWidth + 40, 800 );
					break;
				case 'decrease':
					newWidth = Math.max( currentWidth - 40, 100 );
					break;
			}

			selectedElement.style.width = newWidth + 'px';
			selectedElement.style.height = 'auto';
			selectedElement.style.maxWidth = '100%';
		} );
	};

	const handleRemove = () => {
		if ( ! selectedElement ) {
			return;
		}

		try {
			if (
				confirm( 'Are you sure you want to remove this media element?' )
			) {
				selectedElement.remove();
				onClose();
				onUpdate();
			}
		} catch ( error ) {
			console.warn( 'Error removing element:', error );
		}
	};

	if ( ! isOpen || ! selectedElement ) {
		return null;
	}

	const currentFloat = elementStyles.float;
	const currentAlign = elementStyles.textAlign;
	const currentWidth = elementStyles.width;

	return (
		<>
			<div
				ref={ controlsRef }
				className="quizpress-media-controls-overlay"
				style={ {
					left: position.left + 'px',
				} }
				onClick={ ( e ) => e.stopPropagation() }
			>
				<div className="quizpress-media-controls-overlay__resize">
					<span className="quizpress-sub-title">
						{ __( 'Resize:', 'easy-content-manager' ) }
					</span>
					<button
						type="button"
						onClick={ () => handleResize( 'decrease' ) }
						className="quizpress-media-controls-overlay__btn-common"
					>
						<svg
							width="16"
							height="16"
							viewBox="0 0 24 24"
							fill="currentColor"
						>
							<path d="M19 13H5v-2h14v2z" />
						</svg>
					</button>
					<button
						type="button"
						onClick={ () => handleResize( 'increase' ) }
						className="quizpress-media-controls-overlay__btn-common"
					>
						<svg
							width="16"
							height="16"
							viewBox="0 0 24 24"
							fill="currentColor"
						>
							<path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
						</svg>
					</button>
				</div>

				<div className="quizpress-media-controls-overlay__divider" />

				<div className="quizpress-media-controls-overlay__width">
					<span className="quizpress-sub-title">
						{ __( 'Width:', 'easy-content-manager' ) }
					</span>

					<Select
						className="quizpress-select quizpress-select--editor-select-width"
						classNamePrefix="quizpress-react-select"
						options={ widthsList }
						value={ widthsList.find(
							( width ) => width.value === currentWidth
						) }
						onChange={ ( width ) =>
							handleWidthChange( width.value )
						}
						isClearable={ true }
					/>
				</div>

				<div className="quizpress-media-controls-overlay__divider" />

				<div className="quizpress-media-controls-overlay__position">
					<span className="quizpress-sub-title">
						{ __( 'Position:', 'easy-content-manager' ) }
					</span>
					<Select
						className="quizpress-select quizpress-select--editor-select-float"
						classNamePrefix="quizpress-react-select"
						options={ alignmentList }
						value={ alignmentList.find(
							( alignment ) => alignment.value === currentFloat
						) }
						menuIsOpen
						onChange={ ( alignment ) => {
							handlePositionChange( alignment.value );
						} }
						isClearable={ true }
					/>
				</div>

				<div className="quizpress-media-controls-overlay__divider" />

				<button
					type="button"
					onClick={ handleRemove }
					className="quizpress-media-controls-overlay__delete"
				>
					<span className="quizpress-icon quizpress-icon--delete" />
				</button>

				<button
					type="button"
					onClick={ onClose }
					className="quizpress-media-controls-overlay__close"
				>
					<span className="quizpress-icon quizpress-icon--close" />
				</button>
			</div>
		</>
	);
};

export default MediaControls;
