import {
	useState,
} from '@wordpress/element';
import {
	Flex,
	FlexItem,
	ColorPicker,
	Popover,
	Button,
} from '@wordpress/components';

import { useControlSettingSet } from '../_hooks';

import { __ } from '@wordpress/i18n';

type PaletteOverride = {
	slug: string,
	color: string,
};

type Props = {
	controlSetting: any,
	values: PaletteOverride[],
	palette: paletteColor[],
	title: string,
	description?: string,
}

function mergePalette(palette: paletteColor[], overrides: PaletteOverride[]) {
	const overrideMap = new Map((overrides || []).map((item) => [item.slug, item.color]));

	return palette.map((item) => ({
		...item,
		color: overrideMap.get(item.slug) || item.color,
	}));
}

function buildOverrides(palette: paletteColor[], defaults: paletteColor[]) {
	return palette.reduce<PaletteOverride[]>((result, item, index) => {
		if (item.color !== defaults[index]?.color) {
			result.push({
				slug: item.slug,
				color: item.color,
			});
		}

		return result;
	}, []);
}

export default function ApuraPaletteOverrides({controlSetting, values, palette: defaults, title, description}: Props) {
	const [isVisible, setIsVisible] = useState<number>(-1);
	const [palette, setPalette] = useState<paletteColor[]>(mergePalette(defaults || [], values || []));

	useControlSettingSet({
		controlSetting,
		value: buildOverrides(palette, defaults || [])
	});

	if (!defaults?.length) {
		return null;
	}

	const toggleVisible = (index:number) => {
		setIsVisible( index );
	};

	const handleColorChange = (newColor: string, index: number) => {
		setPalette((prevPalette) =>
			prevPalette.map((item, i) =>
				i === index ? { ...item, color: newColor } : item
			)
		);
	}

	const handleResetClick = (index:number) => {
		setPalette((prevPalette) =>
			prevPalette.map((item, i) =>
				i === index ? defaults[i] : item
			)
		);
	}

	return (
		<div className='apura-palette-overrides'>
			<label className="apura-control-title">{title}</label>
			{description &&
				<p className='description customize-control-description'>{description}</p>
			}
			{palette.length > 0 && palette.map((paletteColor, index) => {
				return (
					<div className='apura-color-control' key={paletteColor.slug}>
						<Flex>
							<FlexItem>
								<label className="apura-control-title">{paletteColor.name}</label>
							</FlexItem>
							<FlexItem>
								<Button
									className='apura-color-control__button'
									onClick={ () => toggleVisible(index) }
									aria-label={title}
									style={paletteColor.color ? {background:paletteColor.color} : undefined}
								></Button>
								{isVisible === index &&
									<Popover
										onClose={() => setIsVisible( -1 ) }
									>
										<div style={{padding:'6px'}}>
											<ColorPicker
												color={paletteColor.color}
												enableAlpha
												onChange={(color) => handleColorChange(color, index)}
												/>
										</div>
										<Button
											variant="primary"
											className='apura-color-control__reset'
											onClick={() => handleResetClick(index)}
										>
											{__('Reset', 'apura')}
										</Button>
									</Popover>
								}
							</FlexItem>
						</Flex>
					</div>
				)
			})
			}
		</div>
	);
}
