import * as React from 'react'
import {__, _x} from '@wordpress/i18n'

import {
	useMemo,
} from '@wordpress/element'

import {
	colord,
} from 'colord'

import Radio from '../radio'

import {
	useSkaBlocks,
} from '../../hooks'

export interface OpacityProps {
	value: number
	rawValue?: string
	defaultValue?: number
	onChange: (nextOpacity: number) => void
}

const Opacity: React.FC<OpacityProps> = ({
	value,
	rawValue,
	defaultValue = 100,
	onChange,
}) => {

	const opacities = useSkaBlocks().compiler.opacities

	const options = useMemo(() => {
		return opacities.map(opacity => ({
			label: opacity,
			tooltip: (Number(opacity) / 100).toString(),
			value: opacity,
		})).concat({
			label: 'DEFAULT',
			tooltip: rawValue ? colord(rawValue).rgba.a.toString() : (Number(defaultValue) / 100).toString(),
			value: `101`,
		})
	}, [opacities, defaultValue, rawValue])

	return (
		<Radio
			label={__('Opacity', 'ska-blocks')}
			pills
			isSmall
			supports={{}}
			options={options}
			value={Number(value).toString()}
			onChange={nextOpacity => {
				const nextValue = parseFloat(nextOpacity)
				onChange(isNaN(nextValue) ? 101 : nextValue)
			}}
		/>
	)
}

export default Opacity
