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

import {
	useEffect,
	useContext,
} from '@wordpress/element'

import {
	RangeControl,
	__experimentalVStack as VStack,
} from '@wordpress/components'

import {
	ButtonGroup,
	FontControlsProps,
	FontControlStringsContext,
	FontSource,
} from '@ska/components'

interface VariableGoogleFont {
	name: string
	wght: {
		min: number
		max: number
		defaultValue: number
	}
	supports: string[] // 'regular', 'italic'
}

export interface VariableGoogleFontControlsProps extends Omit<FontControlsProps, 'font'> {
	font: VariableGoogleFont
}

const Controls: React.FC<VariableGoogleFontControlsProps> = ({
	font,
	value,
	onChange,
}) => {

	const {
		minWghtLabel,
		maxWghtLabel,
	} = useContext(FontControlStringsContext)

	const {
		// subsets = [],
		wght = {
			min: 400,
			max: 400,
		},
		supports = ['regular'],
	} = font

	const {
		min = 400,
		max = 400,
	} = wght

	const {
		wght: currentWght = {},
		types = ['regular'],
	} = value

	const takeWght = (input: number = 0): number => {
		return Math.max(Math.min(input, max), min)
	}

	/** Ensure `min` and `max` default values are defined in config object. */
	useEffect(() => {
		if(!currentWght.min || !currentWght.max) {
			onChange({
				...value,
				wght: {
					min,
					max,
					...currentWght,
				},
			})
		}
	}, [currentWght, min, max, value, onChange])

	return (
		<VStack spacing={4}>
			{supports.length > 0 && (
				<ButtonGroup
					pills
					isSmall
					label={__('Types', 'ska-blocks')}
					options={supports.map(type => ({
						label: type,
						value: type,
					}))}
					value={types}
					onChange={nextTypes => {
						onChange({
							...value,
							types: [
								...nextTypes,
							],
						})
					}}
				/>
			)}
			{min < 400 && (
				<RangeControl
					label={minWghtLabel}
					min={min}
					max={400}
					value={currentWght.min || min}
					step={100}
					marks
					onChange={nextMin => {
						onChange({
							...value,
							wght: {
								...currentWght,
								min: takeWght(nextMin),
							},
						})
					}}
					__nextHasNoMarginBottom
					__next40pxDefaultSize
				/>
			)}
			{max > 400 && (
				<RangeControl
					label={maxWghtLabel}
					min={400}
					max={max}
					value={currentWght.max || max}
					step={100}
					marks
					onChange={nextMax => {
						onChange({
							...value,
							wght: {
								...currentWght,
								max: takeWght(nextMax),
							},
						})
					}}
					__nextHasNoMarginBottom
					__next40pxDefaultSize
				/>
			)}
		</VStack>
	)
}

const Source: FontSource = {
	id: 'variableGoogleFonts',
	label: __('Variable Google Font', 'ska-components'),
	fonts: [],
	renderControls: Controls,
}

export default Source
