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

import {
	hasBlockSupport,
	// @ts-expect-error
} from '@wordpress/blocks'

import {
	createHigherOrderComponent,
} from '@wordpress/compose'

import {
	addFilter,
} from '@wordpress/hooks'

import {
	InspectorControlsProps,
} from '../../tailwind/inspector-controls'

import type {
	tBlockNameOrType,
	tBlockType,
} from '@ska/shared'

import {
	SelectorsInspectorControls,
} from './components'

import {
	withSelectorsClassNames,
} from './util'

export * from './components'
export * from './hooks'
export * from './types'
export * from './util'

const hasSelectorsSupport = (block: tBlockNameOrType) => hasBlockSupport(block, 'customClassName', true)

const withCustomAttributes = (settings: tBlockType) => {

	if(!hasSelectorsSupport(settings)) {
		return settings
	}

	if(!settings.attributes.skaBlocksSelectors) {
		Object.assign(settings.attributes, {
			skaBlocksSelectors: {
				type: 'object',
			},
		})
	}

	if(!settings.attributes.skaBlocksOptions) {
		Object.assign(settings.attributes, {
			skaBlocksOptions: {
				type: 'object',
			},
		})
	}

	return settings
}

const withSelectorsControls = createHigherOrderComponent(
	(BaseInspectorControls: React.FC<InspectorControlsProps>) => (props: InspectorControlsProps) => {

		const {
			children,
			...restProps
		} = props

		return (
			<BaseInspectorControls {...restProps}>
				{children}
				<SelectorsInspectorControls />
			</BaseInspectorControls>
		)
	},
	'withSkaBlocksSelectorsControls'
)

export default () => {
	addFilter('blocks.registerBlockType', 'ska-blocks/with-selectors-attributes', withCustomAttributes)
	addFilter('ska.blocks.InspectorControls', 'ska-blocks/with-selectors-controls', withSelectorsControls)
	addFilter('ska.blocks.getTailwindClasses', 'ska-blocks/with-selectors-class-names', withSelectorsClassNames)
}
