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

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

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

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

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

import {
	VariationsInspectorControls,
	VariationsLoader,
} from './components'

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

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

export const hasVariationsSupport = (block: tBlockNameOrType) => {
	/** Unable to use Paragraph block's registered variations for some reason. */
	const isParagraphBlock = typeof block === 'string' ? block === 'core/paragraph' : block.name === 'core/paragraph'
	return (
		!isParagraphBlock
		&& hasBlockSupport(block, 'customClassName', true)
		&& hasBlockSupport(block, 'skaBlocksVariation', true)
	)
}

const withCustomAttributes = (settings: tBlockType) => {

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

	if(!settings.attributes.skaBlocksVariation) {
		Object.assign(settings.attributes, {
			skaBlocksVariation: {
				type: ['number', 'string'],
			},
		})
	}

	return settings
}

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

		const {
			children,
			...restProps
		} = props

		const {
			blockProps,
		} = restProps

		const {
			name: blockName,
		} = blockProps

		if(!hasVariationsSupport(blockName)) {
			return <BaseInspectorControls {...props} />
		}

		return (
			<BaseInspectorControls {...restProps}>
				{children}
				<VariationsInspectorControls />
			</BaseInspectorControls>
		)
	},
	'withSkaBlocksVariationsInspectorControls'
)

const withVariationsLoader = createHigherOrderComponent(
	(Component: any) => (props: any) => {
		return <>
			<Component {...props} />
			<VariationsLoader />
		</>
	},
	'withSkaBlocksVariations'
)

export default () => {
	addFilter('blocks.registerBlockType', 'ska-blocks/with-variation-attribute', withCustomAttributes)
	addFilter('ska.blocks.InspectorControls', 'ska-blocks/with-variations-inspector-controls', withVariationsInspectorControls)
	addFilter('ska.blocks.globalPlugin', 'ska-blocks/with-variations-loader', withVariationsLoader)
}
