import {
	useState,
	useEffect,
} from '@wordpress/element';
import {
	Flex,
	FlexItem,
	FlexBlock,
	ColorPicker,
	Popover,
	Button,
	Modal,
	TextControl,
	ButtonGroup,
} from '@wordpress/components';

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

import { __, sprintf, _x } from '@wordpress/i18n';

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

export default function ApuraCustomPalette({controlSetting, values, resetDefaults, title, description}: Props) {
	const [isColorPickerOpen, setIsColorPickerOpen] = useState<number>(-1);
	const [items, setItems] = useState<paletteColor[]>(values || []);
	const [isDeleteMsgOpen, setDeleteMsgOpen] = useState<number>(-1);
	const [nameEdit, setNameEdit] = useState<{index:number, name:string}|null>(null);

	useControlSettingSet({
		controlSetting,
		value: items
	});

	const handleAddItem = () => {
		let lastNum = 0;
		if (items.length > 0) {
			lastNum = parseInt(items[items.length - 1].slug.replace(/[^0-9]/g, ''));
		}
		const newItem: paletteColor = { name: `Custom ${lastNum + 1}`, slug: `ap-custom-${lastNum + 1}`, color: '#ffffff' };
		setItems([...items, newItem]);
	};

	const handleRemoveItem = (index: number) => {
		const newItems = items.filter((_, i) => i !== index);
		setItems(newItems);
		setDeleteMsgOpen(-1);
	}

	const openDeleteMsg = (index: number) => setDeleteMsgOpen(index);
	const closeDeleteMsg = () => setDeleteMsgOpen(-1);

	const handleNameEditClick = (index: number) => {
		setNameEdit({index, name: ''});
	};

	const handleNameEditCancelClick = (index: number) => {
		setNameEdit(null);
	};

	const handleNameChange = (index: number, name: string) => {
		setNameEdit({index, name});
	}

	const handleNameSaveClick = (index: number) => {
		if (nameEdit?.index !== index || !nameEdit?.name) return;

		const newItems = items.map((item, i) =>
			i === index ? { ...item, name: nameEdit.name } : item
		);

		setItems(newItems);
		setNameEdit(null);
	}

	const handleItemChange = (index:number, field:string, fieldValue:string) => {
		const newItems = items.map((item, i) =>
			i === index ? { ...item, [field]: fieldValue } : item
		);
		setItems(newItems);
	};

	const handleColorPickerVisible = (index:number) => {
		setIsColorPickerOpen( index );
	};

	return (
		<div className='apura-custom-palette'>
			<label className="apura-control-title">{title}</label>
			{description &&
				<p className='description customize-control-description'>{description}</p>
			}
			<Button
				style={{ justifyContent: 'center', width: '100%' }}
				variant='secondary'
				icon={<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 24 24"><path fill="currentColor" d="M11.5 12.5H6v-1h5.5V6h1v5.5H18v1h-5.5V18h-1v-5.5Z" /></svg>}
				iconPosition='right'
				onClick={handleAddItem}
				/* translators: %s is the name of the item to add */
			>{sprintf(__('Add %s', 'apura'), 'Custom Color')}</Button>
			{items.map((item, index) => (
				<div className='apura-color-control apura-custom-palette__item'>
					<Flex key={item.slug}>
						<FlexItem>
							<div className='apura-editable-field'>
								<input
									type='text'
									className='apura-editable-field__input'
									readOnly={nameEdit?.index !== index}
									value={(nameEdit?.index === index && nameEdit?.name) ? nameEdit?.name : item.name}
									onChange={(e) => {handleNameChange(index, e.target.value) }}
								/>
								{nameEdit?.index === index ? (
									<ButtonGroup className='apura-editable-field__edit-actions'>
										<Button size="small" variant='primary' iconSize={20} icon={<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M15.3 5.29999L8.49999 12.1L5.69999 9.29999L4.29999 10.7L8.49999 14.9L16.7 6.69999L15.3 5.29999Z" fill="currentColor" /></svg>} onClick={() => handleNameSaveClick(index)} label={__('Save')} />
										<Button size="small" variant='secondary' iconSize={20} icon={<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M14.95 6.45999L11.41 9.99999L14.95 13.54L13.54 14.95L9.99999 11.42L6.46999 14.95L5.04999 13.53L8.57999 9.99999L5.04999 6.46999L6.46999 5.04999L9.99999 8.57999L13.54 5.04999L14.95 6.45999Z" fill="currentColor" /></svg>} onClick={() => handleNameEditCancelClick(index)} label={__('Cancel')} />
									</ButtonGroup>
									) : (
										<Button className='apura-editable-field__edit' iconSize={20} icon={<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M13.89 3.39L16.6 6.11C17.06 6.57 17.02 7.35 16.63 7.75L8.62 15.77L3.06 16.93L4.22 11.35C4.22 11.35 11.82 3.72 12.21 3.32C12.6 2.93 13.43 2.93 13.89 3.39ZM11.16 6.18L5.57 11.79L6.68 12.9L12.22 7.25L11.16 6.18ZM8.19 14.41L13.77 8.81L12.7 7.73L7.11 13.33L8.19 14.41Z" fill="currentColor" /></svg>} label={__('Edit')} onClick={() => handleNameEditClick(index)} />
								 )}
							</div>
						</FlexItem>
						<FlexItem>
							<Button className='apura-color-control__button' onClick={ () => handleColorPickerVisible(index) } aria-label={title} style={item.color ? {background:item.color} : undefined} />
							{isColorPickerOpen === index &&
								<Popover onClose={() => setIsColorPickerOpen( -1 ) }>
									<div style={{padding:'6px'}}>
										<ColorPicker color={item.color} enableAlpha onChange={(color) => handleItemChange(index, 'color', color)} />
									</div>
								</Popover>
							}
						</FlexItem>
						<FlexItem>
							<Button className='apura-color-control__remove' size='small' iconSize={20} icon={<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 4H15C15.6 4 16 4.4 16 5V6H3V5C3 4.4 3.5 4 4 4H7C7.2 2.9 8.3 2 9.5 2C10.7 2 11.8 2.9 12 4ZM8 4H11C10.8 3.4 10.1 3 9.5 3C8.9 3 8.2 3.4 8 4ZM4 7H15L14.1 17.1C14.1 17.6 13.6 18 13.1 18H5.9C5.4 18 5 17.6 4.9 17.1L4 7Z" fill="currentColor"/></svg>} label={__('Remove')} onClick={() => openDeleteMsg(index)} />
						</FlexItem>
					</Flex>
					{isDeleteMsgOpen === index && (
						<Modal title={sprintf(__('Are you sure you want to delete the %s?', 'apura'), item.name)} onRequestClose={closeDeleteMsg}>
							<p>{__('The color of elements using this color custom property will be undefined.', 'apura')}</p>
							<Flex justify='flex-end'>
								<FlexItem>
									<Button variant='primary' onClick={() => handleRemoveItem(index)}>{__('Remove')}</Button>
								</FlexItem>
								<FlexItem>
									<Button variant='secondary' onClick={closeDeleteMsg}>{__('Cancel')}</Button>
								</FlexItem>
							</Flex>
						</Modal>
					)}
				</div>
			))}
		</div>
	);
}
