import { LabelControl } from './label';
import { useState, useRef, useEffect } from '@wordpress/element';

export const FilterControl = (props) =>{
	const { prop, value, setAttributes } = props;
	const { name } = prop['c'];
	const [isFilterVisible, setFilterVisible] = useState(false);

	var values = !pagelayer_empty(value) ? value :  [0,100,100,0,0,100,100];
	
	if(pagelayer_is_string(values)){
		values = values.split(',');
	}
	
	const filterRef = useRef(null);
	const filters = [['blur','10','0.1'],['brightness','200','1'],['contrast','200','1'],['grayscale','200','1'],['hue','360','1'],['opacity','100','1'],['saturate','200','1']];

	useEffect(() => {
	
		const handleDocumentClick = (e) => {

			if(
				filterRef.current &&
				!filterRef.current.contains(e.target)
			){
				setFilterVisible(false);
			}
		};

		document.addEventListener('click', handleDocumentClick);

		return () => {
			document.removeEventListener('click', handleDocumentClick);
		};
	}, []);

	// Convert the jQuery function to a React method
	const handleInputChange = (index,e) => {

		const newValue = parseFloat(e.target.value);

		let newValues = [...values];

		newValues[index] = newValue;
		
		setAttributes({[name]: newValues});
	};

	return (
		<div className="components-base-control pagelayer-base-control">
			<LabelControl {...props}/>
			<div className="pagelayer-prop-holder" ref={filterRef}>
				<span 
					className="pagelayer-prop-edit" 
					onClick={() => setFilterVisible(!isFilterVisible)}
				>
				<i className="pli pli-pencil"></i></span>
				{ isFilterVisible && <div className="pagelayer-elp-filter-div">
					{ filters.map((obj, key) => (
						
						<div className={`pagelayer-elp-prop-grp pagelayer-elp-filter-${filters[key][0]}`}>
							<label className="pagelayer-elp-label">{filters[key][0]}</label>
							<input 
								className={`pagelayer-elp-slider pagelayer-elp-filter-input pagelayer-elp-filter-${filters[key][0]}`}
								type="range" 
								max={filters[key][1]}
								min="0" 
								step={filters[key][2]}
								value={values[key]}
								onChange={(e) => handleInputChange(key, e)}
							/>
							<span className="pagelayer-elp-filter-val"></span>
						</div>
					))
					}
					</div>
				}
			</div>
		</div>
	);
}

