import type { EditorState } from '../richTextTypes'
import { createCommandExecutor, createCommandRegistry } from '../utils/commands'
import { isStyleActive } from '../utils/selection'

export function useCommands(state: EditorState, debug?: { logCommand: (command: string, value?: string) => void }) {
	const commands = createCommandRegistry(state)
	const executor = createCommandExecutor(state, commands)

	// Function to immediately update styles
	const updateStylesImmediately = () => {
		if (!state.doc) { return }

		const styles = new Set<string>()
		const styleTypes = [
			'bold',
			'italic',
			'underline',
			'link',
			'h1',
			'h2',
			'h3',
			'h4',
			'h5',
			'h6',
			'blockquote',
			'p',
			'orderedList',
			'unorderedList',
			'alignLeft',
			'alignCenter',
			'alignRight',
			'alignJustify',
			'textDirection',
			'ltrDirection',
			'rtlDirection'
		]

		styleTypes.forEach((style) => {
			if (isStyleActive(style, state.doc!)) {
				styles.add(style)
			}
		})

		state.selectedStyles = styles
	}

	return {
		execute: (command: string, value?: string) => {
			if (!state.doc) {
				console.log('[useCommands] No document available, skipping command')
				return
			}

			// Log command if debug is enabled
			debug?.logCommand(command, value)

			// Handle view state commands directly (these don't need DOM manipulation)
			if (['splitView', 'codeView', 'fullScreen'].includes(command)) {
				switch (command) {
					case 'splitView':
						state.isSplitView = !state.isSplitView
						return
					case 'codeView':
						state.isCodeView = !state.isCodeView
						return
					case 'fullScreen':
						state.isFullscreen = !state.isFullscreen
						return
				}
			}

			// Focus the editor before executing command
			try {
				state.doc.body.focus()
			} catch (e) {
				console.error('[useCommands] Error focusing editor:', e)
			}

			// Update current selection state before command execution
			const selection = state.doc.getSelection()
			if (selection?.rangeCount) {
				state.selection = selection
				state.range = selection.getRangeAt(0).cloneRange()
				state.rangeCount = selection.rangeCount
			}

			// Execute the command
			try {
				executor.execute(command, value)

				// Update styles immediately after command execution for all commands except view state
				const viewCommands = ['splitView', 'codeView', 'fullScreen']
				if (!viewCommands.includes(command)) {
					updateStylesImmediately()
				}
			} catch (e) {
				console.error('[useCommands] Error during command execution:', e)
			}
		},
		isActive: executor.isActive,
		getValue: executor.getValue
	}
}
