import { useState } from '@wordpress/element';
import {
	Button,
} from '@wordpress/components';

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

type Props = {
	controlSetting: any, // wp.customize.setting or wp.customize.settings[key]
	choices: {
		[key: string]: string
	},
	value: string,
	title: string,
	description?: string,
}


export default function ApuraButtonGroup({ controlSetting, choices, value, title, description }: Props) {

	const buttons = Object.entries(choices).map(([key, label]) => ({ label, value: key }));

	const [selected, setSelected] = useState<string | undefined>(value);

	useControlSettingSet({
		controlSetting,
		value: selected
	});

	const handleOnClick = (value: string) => {
		setSelected(value);
	}

	return (
		<div className='apura-button-group-control'>
			{title && <span className="customize-control-title">{title}</span>}
			{description &&
				<p className='description customize-control-description'>{description}</p>
			}
			<div className='apura-button-group'>
				{buttons.length > 0 && buttons.map(item => {
					return (
						<span key={item.value} className='apura-button-group__item'>
							<Button
								className='apura-button'
								label={item.label}
								showTooltip={true}
								isPressed={item.value === selected}
								onClick={() => handleOnClick(item.value)}
							>
								{item.label}
							</Button>
						</span>
					)
				})}
			</div>
		</div>
	)
}
