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

import {
	Modal,
	__experimentalUseNavigator as useNavigator,
	__experimentalNavigatorButton as NavigatorButton,
	__experimentalView as View,
	__experimentalHStack as HStack,
	__experimentalVStack as VStack,
} from '@wordpress/components'

import {
	sanitizeURIComponent,
} from '@ska/utils'

import {
	getSelectorDisplayName,
	type SelectorsValue,
} from '..'

export interface SelectorsDetailsModalProps {
	value: SelectorsValue
	onRequestClose: () => void
}

interface SelectorTreeNode {
	selector: string
	children: SelectorsTree
}

type SelectorsTree = SelectorTreeNode[]

const buildSelectorsTree = (selectors: SelectorsValue = {}): SelectorsTree => {

	return Object.keys(selectors).reduce((acc, cur) => {

		const {
			skaBlocksSelectors = {},
		} = selectors[cur]

		const node: SelectorTreeNode = {
			selector: cur,
			children: buildSelectorsTree(skaBlocksSelectors),
		}

		return [
			...acc,
			node,
		]
	}, [] as SelectorsTree)
}

interface TreeNodeProps {
	selector: SelectorTreeNode['selector']
	children?: SelectorsTree
	level?: number
	path: string
}

const TreeNode: React.FC<TreeNodeProps> = ({
	selector,
	children = [],
	level = 0,
	path = '',
}) => {

	const nextPath = `${path}/${sanitizeURIComponent(selector)}`

	return (
		<View
			className='ska-blocks__selector__details'
			style={{marginTop: 2}}
		>
			<HStack
				alignment='start'
				justify='start'
			>
				<View style={{paddingLeft: level * 28}}>
					{level > 0 && <span style={{marginRight: 5}}> </span>} {/* Spacing */}
					{level > 1 && ' '.repeat(level - 1)} {/* Additional spacing for deeper levels */}
					{level > 0 && '└─'} {/* Connector */}
				</View>
				<NavigatorButton
					variant={'secondary'}
					size={level === 0 ? 'compact' : 'small'}
					children={getSelectorDisplayName(selector)}
					path={nextPath}
				/>
			</HStack>
			{children.map(node => {
				return (
					<TreeNode
						key={node.selector}
						selector={node.selector}
						children={node.children}
						level={level + 1}
						path={nextPath}
					/>
				)
			})}
		</View>
	)
}

const SelectorsDetailsModal: React.FC<SelectorsDetailsModalProps> = ({
	value,
	onRequestClose,
}) => {

	const navigator = useNavigator()
	const currentPath = navigator?.location?.path || '/'
	const nextPath = currentPath === '/' ? '/selector' : currentPath
	const tree = buildSelectorsTree(value)

	return (
		<Modal
			title={__('Selectors', 'ska-blocks')}
			onRequestClose={onRequestClose}
			size='medium'
		>
			<VStack spacing={8}>
				{tree.map((node, index) => (
					<TreeNode
						key={index}
						selector={node.selector}
						children={node.children}
						path={nextPath}
					/>
				))}
			</VStack>
		</Modal>
	)
}

export default SelectorsDetailsModal
