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

import {
	Button,
	__experimentalNumberControl as NumberControl,
} from '@wordpress/components'

import {
	shuffle as shuffleIcon,
	seen as seenIcon,
} from '@wordpress/icons'

import {
	getPlaceholderSvg,
} from '@ska/shared'

import {
	maxPlaceholderImage,
	placeholderImageUrl,
} from '../../data'

import {
	usePluginPreference,
} from '../../store'

import './style.scss'

export interface PlaceholderImageControlProps {
	value: number
	onChange: (nextValue: number) => void
	showPlaceholderImageToggle?: boolean
}

const PlaceholderImageControl: React.FC<PlaceholderImageControlProps> = ({
	value,
	onChange,
	showPlaceholderImageToggle = false,
}) => {

	const [showPlaceholderImage, setShowPlaceholderImage] = usePluginPreference('showPlaceholderImage')

	if(!placeholderImageUrl) {
		return null
	}

	return (
		<div className='ska-placeholder-image-control'>
			<NumberControl
				label={__('Placeholder image index', 'ska-blocks')}
				help={__('Specify an index to use a bundled placeholder image.', 'ska-blocks')}
				value={value}
				min={0}
				step={1}
				max={maxPlaceholderImage}
				isDragEnabled={false}
				onChange={nextValue => onChange(parseInt(nextValue || '0'))}
				suffix={<>
					<Button
						children={__('Randomize', 'ska-blocks')}
						icon={shuffleIcon}
						iconPosition='right'
						iconSize={20}
						onClick={() => onChange(Math.floor(Math.random() * maxPlaceholderImage) + 1)}
					/>
				</>}
				__next40pxDefaultSize
			/>
			<div className='ska-placeholder-image-control__placeholder'>
				{value > 0 ? (
					<img
						decoding='async'
						// @ts-expect-error
						src={sprintf(placeholderImageUrl, value)}
						aria-hidden='true'
					/>
				) : (
					<div
						dangerouslySetInnerHTML={{
							__html: getPlaceholderSvg(),
						}}
					/>
				)}
			</div>
			{showPlaceholderImageToggle && <>
				<Button
					className='ska-placeholder-image-control__preview-toggle'
					size='small'
					label={showPlaceholderImage ? __('Show media picker', 'ska-blocks') : __('Show placeholder image', 'ska-blocks')}
					icon={seenIcon}
					isPressed={showPlaceholderImage}
					onClick={() => setShowPlaceholderImage(!showPlaceholderImage)}
				/>
			</>}
		</div>
	)
}

export default PlaceholderImageControl
