import { useState, useEffect, memo } from '@wordpress/element';
import {
	RangeControl,
	Button,
	Flex,
	FlexBlock,
	FlexItem,
	Dashicon
} from '@wordpress/components';

import DeviceControl from './DeviceControl';
import UnitField from './UnitField';
import { usePreviewedDevice } from '../_hooks';
import { __, sprintf } from '@wordpress/i18n';


/**
 * responsiveRangeControl.
 */
type Props = {
	// settings: {
	// 	[key in device]: {
	// 		get: () => string[]
	// 		set: (a:any) => void
	// 	}
	// },
	values: RangeControlDeviceValue[],
	defaults: RangeControlDeviceValue[],
	devices: devices,
	unitData: unitData[],
	label: string,
	unitOptions: unitOptions,
	onChange: (newValues: {[key in device]: string}) => void
}

export default function ApuraRangeControl({
	values,
	defaults,
	devices,
	unitData,
	label,
	unitOptions,
	onChange
}: Props) {

	// console.log(values);

	const [rangeValues, setRangeValues] = useState(values || defaults);
	const { previewedDevice, setPreviewedDevice, handleDeviceClick } = usePreviewedDevice();

	useEffect(() => {
		// console.log('currentValues', rangeValues);
		const cssValues: {[key in device]: string} = {desktop: '', tablet:'', mobile: ''};
		// wp.customize API Set value.
		rangeValues.forEach(rangeValue => {
			const _device = rangeValue.device;
			// console.log(rangeValue.number);
			let value = '';
			if (rangeValue.number) {
				// unitが「-」の場合はunitなし。
				let unit = rangeValue.unit === '-' ? '' : rangeValue.unit;
				value = String(rangeValue.number) + unit;
			}

			// console.log(value);
			cssValues[_device] = value;
		});
		onChange(cssValues);
	}, [rangeValues]);



	// デバイス毎にスライダーの変更イベント.
	function handleNumberChange(newNum: number|undefined, device: device) {
		const newValues = rangeValues.map((_values, i) =>{
			if (_values.device === device) {
				// Return a new number
				return {
					..._values,
					number: newNum,
				};
			} else {
				 // No change
				return _values;
			}
		});
		// Re-render with the new array
		setRangeValues(newValues);
	}

	// デバイス毎にユニットの変更イベント.
	const handleUnitChange: handleUnitChange = function (newUnit: string, device: device) {
		const newValues = rangeValues.map((_values, i) => {
			if (_values.device === device) {
				let currentUnitData: unitData = unitData.find((item: unitData) => item.value === newUnit) || {value: ''};
				// ユニットありで変えた場合にmax以上の値だった場合はmax値にnumberを変える.
				let _number = _values.number;
				if (currentUnitData?.max &&_values?.number && _values.number > currentUnitData.max) {
					_number = currentUnitData.max;
				}
				// Return a new unit
				return {
					..._values,
					number: _number,
					unit: newUnit,
					min: currentUnitData?.min || 0,
					max: currentUnitData?.max || 100,
					step: currentUnitData?.step || 1,
				};
			} else {
				 // No change
				return _values;
			}
		});
		// Re-render with the new array
		setRangeValues(newValues);
	}

	// デバイス毎にリセットする.
	function handleResetClick(device: device) {
		const newValues = rangeValues.map((_values, i) =>{
			if (_values.device === device) {
				const _defaultData = defaults.find((item) => item.device === device);
				// Return default values.
				return {
					..._values,
					number: _defaultData?.number,
					unit: _defaultData?.unit || '',
					min: _defaultData?.min || 0,
					max: _defaultData?.max || 100,
				};
			} else {
				 // No change
				return _values;
			}
		});
		// Re-render with the new array
		setRangeValues(newValues);
	}



	/**
	 * Range control field.
	 *
	 * @param {Object} rangeValue
	 * @returns {React.ReactElement}
	 */
	const rangeField = (rangeValue: RangeControlDeviceValue) => {
		// const step = rangeValue.unit && rangeValue.unit !== 'px' ? 0.1 : 1;
		return(
		<Flex className='apura-control-field-wrap' key={rangeValue.device} gap={1}>
			<FlexBlock>
				<RangeControl
					__next40pxDefaultSize
					__nextHasNoMarginBottom
					value={rangeValue.number || undefined}
					max={rangeValue.max}
					min={rangeValue.min}
					step={rangeValue.step}
					onChange={( value ) => {
						handleNumberChange(value, rangeValue.device);
					}}
				/>
			</FlexBlock>
			<FlexItem>
				<Button
					className='apura-reset-button'
					icon={<Dashicon icon={'image-rotate'} size={15} />}
					iconSize={16}
					size='small'
					label={__('Reset', 'apura')}
					onClick={ () =>{
						handleResetClick(rangeValue.device);
					} }
				/>
			</FlexItem>
		</Flex>
		);
	}

  return (
		<div className='apura-range-control'>
			<div className="apura-control-header">
				<div className="apura-control-header__title">
					<label className="customize-control-title">{label}</label>
				</div>
				<DeviceControl devices={devices} />
				<div className='apura-control-header__unit'>
					{rangeValues.length > 1 ? rangeValues.map((rangeValue, i) => {
						return rangeValue.device === previewedDevice && (
							<UnitField
								units={unitOptions}
								value={rangeValue.unit}
								device={rangeValue.device}
								onChange={handleUnitChange}
							/>
						)
					})
					:
					<UnitField
						units={unitOptions}
						value={rangeValues[0].unit}
						device={rangeValues[0].device}
						onChange={handleUnitChange}
					/>
					}
				</div>
			</div>

			{rangeValues.length > 1 ? rangeValues.map((rangeValue, i) => {
				return rangeValue.device === previewedDevice && rangeField(rangeValue);
			}) : (
				rangeField(rangeValues[0])
			)
			}
		</div>
  );
}
