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

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

import {
	RecordEditor,
} from '../../../../components'

import type {
	PluginOptions,
} from '../../options'

import ShortcodeValueControl from './ShortcodeValueControl'

import type {
	RenderOptionProps,
} from '@ska/plugin/src/components/options/RenderOption'

import './style.scss'

export type DynamicShortcodesControlProps = RenderOptionProps<PluginOptions, PluginOptions['dynamicShortcodes']>

export const DynamicShortcodesControlContext = createContext<{
	select?: DynamicShortcodesControlProps['select'],
	dispatch?: DynamicShortcodesControlProps['dispatch'],
}>({
	select: undefined,
	dispatch: undefined,
})

const DynamicShortcodesControl: React.FC<DynamicShortcodesControlProps> = props => {

	const {
		id,
		label,
		description = '',
		value = {},
		default: defaultValue = {},
		props: controlProps = {},
		onChange,
		select,
		dispatch,
	} = props

	const {
		lockDefaultValues = true,
		...restControlProps
	} = controlProps

	return (
		<DynamicShortcodesControlContext.Provider value={{select, dispatch}}>
			<RecordEditor
				className='ska-blocks__dynamic-shortcodes'
				id={id}
				label={label}
				help={description}
				size='large'
				value={value}
				onChange={onChange}
				ValueControl={ShortcodeValueControl}
				{...lockDefaultValues && {
					lockedKeys: Object.keys(defaultValue),
				}}
				{...restControlProps}
			/>
		</DynamicShortcodesControlContext.Provider>
	)
}

export default DynamicShortcodesControl
