import {
	useState,
	useMemo
} from '@wordpress/element';
import {
	Flex,
	FlexBlock
} from '@wordpress/components';

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

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


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

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

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

	useControlSettingSet({
		controlSetting,
		value: selected
	});

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

	// 1カラム以外の場合、col に応じたクラスを付与、デフォルトのgapは8px.
	const flexBasis = col && col !== 0 ? `calc(100% / ${col} - (8px * (${col} - 1) / ${col}))` : '';

	return (
		<div className='apura-button-group-control'>
			{title && <span className="customize-control-title">{title}</span>}
			{description &&
				<p className='description customize-control-description'>{description}</p>
			}
			<Flex align='start' wrap={col !== 0}>
			{buttons.length > 0 && buttons.map(item => {
				return (
					<FlexBlock key={item.value} style={flexBasis ? { flexBasis: flexBasis } : {}}>
						<button
							type="button"
							className={selected === item.value ? 'apura-image-button is-active' : 'apura-image-button'}
							aria-label={item.label}
							onClick={() => handleOnClick(item.value)}
						>
							<span className="apura-image-button__image">
								<img
									src={item.image}
									alt={item.label}
									title={item.label}
								/>
							</span>
							<span className="apura-image-button__label">{item.label}</span>
						</button>
					</FlexBlock>
				)
			})}
			</Flex>
		</div>
	)
}
