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 DynamicLinkValueControl from './DynamicLinkValueControl'

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

import './style.scss'

export type DynamicLinksControlProps = RenderOptionProps<PluginOptions, PluginOptions['userDynamicLinks']>

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

const DynamicLinksControl: React.FC<DynamicLinksControlProps> = props => {

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

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

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

export default DynamicLinksControl
