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

export const DimensionControl = (props) =>{
		
	const { prop, label, value, setAttributes } = props;
	const { name } = prop['c'];
	
	var values = !pagelayer_empty(value) ? value : ['', ''];

	if(pagelayer_is_string(values)){
		values = values.split(',');
	}
	
	const [isLinked, setIsLinked] = useState(true);
	const dimensionRef = useRef(null)

	const handleInputChange = (index, e) => {
		
		const newValue = parseFloat(e.target.value);
		
		let newValues = [...values];
		
		if (isLinked) {
			newValues = newValues.map(() => newValue);
		} else {
			newValues[index] = newValue;
		}
		
		if(prop?.units){
			newValues = setUnit(newValues);
		}
		
		setAttributes({[name]: newValues});
		
	};

	const setUnit = (val) => {
		var unit = dimensionRef.current.querySelectorAll('.pagelayer-elp-units .selected')[0].innerHTML;
		if(Array.isArray(val)){
			for(var i in val){
				if(val[i].length < 1){
					continue;
				}
				val[i] = parseFloat(val[i])+unit;
			}
		}else{
			val = parseFloat(val)+unit;
		}
		return val;
	}	


	return (
		<div className="components-base-control pagelayer-base-control" ref={dimensionRef}>
			<LabelControl {...props}/>
			<div className="pagelayer-elp-dimension-div">
				<input
					type="number"
					className="pagelayer-elp-dimension"
					value={parseFloat(values[0])}
					onChange={(e) => handleInputChange(0, e)}
				/>
				<input
					type="number"
					className="pagelayer-elp-dimension"
					value={parseFloat(values[1])}
					onChange={(e) => handleInputChange(1, e)}
				/>
				<i
				className={`pli pli-link${isLinked ? ' pagelayer-elp-padding-linked' : ''}`}
				onClick={ () => setIsLinked(!isLinked) }
				></i>
			</div>
		</div>
	);
}
