import { useState, useRef, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import './styles.scss';
import { defaultColors } from './helper';

const ColorControls = ( { onMouseDownHandler, onClickHandler } ) => {
	const [ showTextColorDropdown, setShowTextColorDropdown ] =
		useState( false );
	const [ showBgColorDropdown, setShowBgColorDropdown ] = useState( false );
	const [ currentTextColor, setCurrentTextColor ] = useState( '#000000' );
	const [ currentBgColor, setCurrentBgColor ] = useState( 'transparent' );
	const textColorRef = useRef( null );
	const bgColorRef = useRef( null );

	const backgroundColors = [
		{ name: 'Transparent', value: 'transparent' },
		...defaultColors,
	];

	const updateCurrentColors = () => {
		try {
			const selection = window.getSelection();
			if ( selection.rangeCount > 0 ) {
				const range = selection.getRangeAt( 0 );
				const parentElement =
					range.commonAncestorContainer.nodeType === 1
						? range.commonAncestorContainer
						: range.commonAncestorContainer.parentElement;

				if ( parentElement ) {
					const computedStyle =
						window.getComputedStyle( parentElement );

					const textColor = computedStyle.color;
					const rgbToHex = ( rgb ) => {
						const result = rgb.match( /\d+/g );
						if ( result && result.length >= 3 ) {
							return (
								'#' +
								(
									( 1 << 24 ) +
									( parseInt( result[ 0 ] ) << 16 ) +
									( parseInt( result[ 1 ] ) << 8 ) +
									parseInt( result[ 2 ] )
								)
									.toString( 16 )
									.slice( 1 )
							);
						}
						return '#000000';
					};

					if ( textColor.startsWith( 'rgb' ) ) {
						setCurrentTextColor( rgbToHex( textColor ) );
					} else if ( textColor.startsWith( '#' ) ) {
						setCurrentTextColor( textColor );
					}

					const bgColor = computedStyle.backgroundColor;
					if (
						bgColor === 'rgba(0, 0, 0, 0)' ||
						bgColor === 'transparent'
					) {
						setCurrentBgColor( 'transparent' );
					} else if ( bgColor.startsWith( 'rgb' ) ) {
						setCurrentBgColor( rgbToHex( bgColor ) );
					} else if ( bgColor.startsWith( '#' ) ) {
						setCurrentBgColor( bgColor );
					}
				}
			}
		} catch ( error ) {
			console.error( 'Color detection failed, using defaults' );
		}
	};

	useEffect( () => {
		const handleSelectionChange = () => {
			updateCurrentColors();
		};

		const handleKeyUp = () => {
			setTimeout( updateCurrentColors, 10 );
		};

		const handleMouseUp = () => {
			setTimeout( updateCurrentColors, 10 );
		};

		document.addEventListener( 'selectionchange', handleSelectionChange );
		document.addEventListener( 'keyup', handleKeyUp );
		document.addEventListener( 'mouseup', handleMouseUp );

		return () => {
			document.removeEventListener(
				'selectionchange',
				handleSelectionChange
			);
			document.removeEventListener( 'keyup', handleKeyUp );
			document.removeEventListener( 'mouseup', handleMouseUp );
		};
	}, [] );

	useEffect( () => {
		const handleClickOutside = ( event ) => {
			if (
				textColorRef.current &&
				! textColorRef.current.contains( event.target )
			) {
				setShowTextColorDropdown( false );
			}
			if (
				bgColorRef.current &&
				! bgColorRef.current.contains( event.target )
			) {
				setShowBgColorDropdown( false );
			}
		};

		document.addEventListener( 'mousedown', handleClickOutside );
		return () => {
			document.removeEventListener( 'mousedown', handleClickOutside );
		};
	}, [] );

	const applyTextColor = ( color ) => {
		document.execCommand( 'foreColor', false, color );
		setCurrentTextColor( color );
		setShowTextColorDropdown( false );
	};

	const applyBackgroundColor = ( color ) => {
		if ( color === 'transparent' ) {
			document.execCommand( 'removeFormat', false, 'backColor' );
		} else {
			document.execCommand( 'hiliteColor', false, color );
		}
		setCurrentBgColor( color );
		setShowBgColorDropdown( false );
	};

	const handleCustomTextColor = ( e ) => {
		if ( e.key === 'Enter' ) {
			const color = e.target.value;
			if ( /^#[0-9A-F]{6}$/i.test( color ) ) {
				applyTextColor( color );
				e.target.value = '';
			} else {
				alert(
					__(
						'Please enter a valid hex color (e.g., #ff0000)',
						'easy-content-manager'
					)
				);
			}
		}
	};

	const handleCustomBgColor = ( e ) => {
		if ( e.key === 'Enter' ) {
			const color = e.target.value;
			if (
				color.toLowerCase() === 'transparent' ||
				/^#[0-9A-F]{6}$/i.test( color )
			) {
				applyBackgroundColor( color );
				e.target.value = '';
			} else {
				alert(
					__(
						'Please enter a valid hex color (e.g., #ff0000) or "transparent"',
						'easy-content-manager'
					)
				);
			}
		}
	};

	return (
		<>
			<div ref={ textColorRef } className="quizpress-color-control">
				<button
					type="button"
					onMouseDown={ ( e ) =>
						onMouseDownHandler( e, () =>
							setShowTextColorDropdown( ! showTextColorDropdown )
						)
					}
					onClick={ onClickHandler }
					className="quizpress-color-control__button quizpress-editor-text-color"
					title={ __( 'Text Color', 'easy-content-manager' ) }
				>
					<span
						className="quizpress-color-control__preview"
						style={ { color: currentTextColor } }
					>
						A ▼
					</span>
				</button>

				{ showTextColorDropdown && (
					<div className="quizpress-color-control__dropdown">
						<div className="quizpress-sub-title">
							{ __( 'Text Color', 'easy-content-manager' ) }
						</div>

						<div className="quizpress-color-control__grid">
							{ defaultColors.map( ( color ) => (
								<button
									key={ color.value }
									type="button"
									onMouseDown={ ( e ) =>
										onMouseDownHandler( e, () =>
											applyTextColor( color.value )
										)
									}
									onClick={ onClickHandler }
									className="quizpress-color-control__swatch"
									style={ { backgroundColor: color.value } }
									title={ color.name }
								/>
							) ) }
						</div>

						<div className="quizpress-color-control__custom">
							<label className="quizpress-color-control__label">
								{ __(
									'Custom Hex Color:',
									'easy-content-manager'
								) }
							</label>
							<input
								type="text"
								placeholder="#000000"
								onKeyPress={ handleCustomTextColor }
								className="quizpress-color-control__input"
							/>
						</div>
					</div>
				) }
			</div>

			<div ref={ bgColorRef } className="quizpress-color-control">
				<button
					type="button"
					onMouseDown={ ( e ) =>
						onMouseDownHandler( e, () =>
							setShowBgColorDropdown( ! showBgColorDropdown )
						)
					}
					onClick={ onClickHandler }
					className="quizpress-color-control__button quizpress-editor-bg-color"
					title={ __( 'Background Color', 'easy-content-manager' ) }
				>
					<span
						className="quizpress-color-control__preview"
						style={ {
							backgroundColor:
								currentBgColor === 'transparent'
									? '#fff'
									: currentBgColor,
							color:
								currentBgColor === 'transparent'
									? '#000'
									: currentBgColor === '#ffffff' ||
									  currentBgColor === '#ffff00'
									? '#000'
									: '#fff',
							border:
								currentBgColor === 'transparent'
									? '1px solid #ddd'
									: 'none',
						} }
					>
						A ▼
					</span>
				</button>

				{ showBgColorDropdown && (
					<div className="quizpress-color-control__dropdown">
						<div className="quizpress-sub-title">
							{ __( 'Background Color', 'easy-content-manager' ) }
						</div>

						<div className="quizpress-color-control__grid">
							{ backgroundColors.map( ( color ) => (
								<button
									key={ color.value }
									type="button"
									onMouseDown={ ( e ) =>
										onMouseDownHandler( e, () =>
											applyBackgroundColor( color.value )
										)
									}
									onClick={ onClickHandler }
									className="quizpress-color-control__swatch"
									style={ {
										backgroundColor:
											color.value === 'transparent'
												? '#fff'
												: color.value,
										border:
											color.value === 'transparent'
												? '1px solid #ddd'
												: '1px solid #ccc',
									} }
									title={ color.name }
								/>
							) ) }
						</div>

						<div className="quizpress-color-control__custom">
							<label className="quizpress-color-control__label">
								{ __(
									'Custom Hex Color or "transparent":',
									'easy-content-manager'
								) }
							</label>
							<input
								type="text"
								placeholder="#ffff00"
								onKeyPress={ handleCustomBgColor }
								className="quizpress-color-control__input"
							/>
						</div>
					</div>
				) }
			</div>
		</>
	);
};

export default ColorControls;
