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

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

import {
	ToggleControl,
	TextControl,
	Modal,
	__experimentalVStack as VStack,
} from '@wordpress/components'

import {
	RecordEditorRecordContext,
} from '@ska/components'

import {
	DynamicLinksControlContext,
} from '.'

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

import './style.scss'

export interface DynamicLinkSettingsModalProps {
	onRequestClose: () => void
}

const DEFAULT_SETTINGS = {
	widget: false,
	label: '',
}

const DynamicLinkSettingsModal: React.FC<DynamicLinkSettingsModalProps> = props => {

	const {
		onRequestClose,
	} = props

	const {
		key,
	} = useContext(RecordEditorRecordContext)

	const {
		select,
		dispatch,
	} = useContext(DynamicLinksControlContext)

	if(!select || !dispatch) {
		return null
	}

	const value = select.getOption('dynamicLinkOptions') as PluginOptions['dynamicLinkOptions']
	const dynamicLinkSettings = value[key] || DEFAULT_SETTINGS

	const {
		widget = false,
		wide = false,
		label = '',
	} = dynamicLinkSettings

	const updateSetting = (settingKey: keyof typeof value, settingValue: any) => {
		dispatch.updateOption({
			option: 'dynamicLinkOptions',
			value: {
				...value,
				[key]: {
					...DEFAULT_SETTINGS,
					...dynamicLinkSettings,
					[settingKey]: settingValue,
				},
			},
		})
	}

	return <>
		<Modal
			title={`${__('Dynamic link settings', 'ska-blocks')}: "${key}"`}
			size='medium'
			className='ska-blocks__dynamic-links__settings'
			onRequestClose={onRequestClose}
		>
			<VStack spacing={4}>
				<ToggleControl
					label={__('Widget', 'ska-blocks')}
					help={__('Display this option in a widget on WordPress admin Dashboard for quick editing.', 'ska-blocks')}
					checked={widget}
					onChange={() => updateSetting('widget', !widget)}
					__nextHasNoMarginBottom
				/>
				{widget && <>
					<ToggleControl
						label={__('Wide', 'ska-blocks')}
						help={__('Render this option full width in the widget.', 'ska-blocks')}
						checked={wide}
						onChange={() => updateSetting('wide', !wide)}
						__nextHasNoMarginBottom
					/>
					<TextControl
						label={__('Label', 'ska-blocks')}
						help={__('Override the display label (in dashboard widget).', 'ska-blocks')}
						placeholder={sprintf(_x('%s link', 'Dynamic link name', 'ska-blocks'), key)}
						value={label}
						onChange={nextValue => updateSetting('label', nextValue)}
						__nextHasNoMarginBottom
						__next40pxDefaultSize
					/>
				</>}
			</VStack>
		</Modal>
	</>
}

export default DynamicLinkSettingsModal
