<script lang="ts" setup>
import type { ToolbarConfig, ToolbarConfigOption, ToolbarOption } from '../richTextTypes'
import { Btn, Dropdown } from '@bagelink/vue'
import { basicToolbarConfig, toolbarOptions } from '../config'
import TableGridSelector from './TableGridSelector.vue'

const {
	config = basicToolbarConfig,
	selectedStyles,
	hideImages = false,
	hideVideos = false,
	hideEmbeds = false,
	hideTables = false,
	hideAlignment = false,
	hideDirections = false,
	hideH5H6 = false,
	hide = []
} = defineProps<{
	config?: ToolbarConfig
	selectedStyles: Set<string>
	hideImages?: boolean
	hideVideos?: boolean
	hideEmbeds?: boolean
	hideTables?: boolean
	hideAlignment?: boolean
	hideDirections?: boolean
	hideH5H6?: boolean
	hide?: string[]
}>()
const emit = defineEmits(['action'])

// Function to get the current alignment icon based on active styles
function getCurrentAlignmentIcon(): string {
	if (selectedStyles.has('alignLeft')) { return 'format_align_left' }
	if (selectedStyles.has('alignCenter')) { return 'format_align_center' }
	if (selectedStyles.has('alignRight')) { return 'format_align_right' }
	if (selectedStyles.has('alignJustify')) { return 'format_align_justify' }
	return 'format_align_left' // default
}

// Function to check if any alignment is active
function isAlignmentActive(): boolean {
	return selectedStyles.has('alignLeft')
		|| selectedStyles.has('alignCenter')
		|| selectedStyles.has('alignRight')
		|| selectedStyles.has('alignJustify')
}

// Helper function to check if an action should be hidden
function shouldHideAction(actionName: string): boolean {
	// Check if it's in the hide array - this covers ALL items including:
	// bold, italic, underline, h1, h2, h3, h4, h5, h6, link, image, video, embed,
	// ul, ol, blockquote, code, clear, direction, table, fullScreen
	if (hide.includes(actionName)) { return true }

	// Alternative name mappings for some actions
	const alternativeNames: Record<string, string[]> = {
		image: ['insertImage', 'image'],
		video: ['insertVideo', 'video'],
		embed: ['insertEmbed', 'embed'],
		table: ['insertTable'],
		direction: ['textDirection'],
		fullScreen: ['fullScreen'],
		ul: ['unorderedList'],
		ol: ['orderedList'],
		splitView: ['splitView'],
		p: ['p'],
		align: ['alignMenu'],
		alignment: ['alignMenu']
	}

	// Check alternative names
	for (const [hideKey, actionNames] of Object.entries(alternativeNames)) {
		if (hide.includes(hideKey) && actionNames.includes(actionName)) {
			return true
		}
	}

	// Map action names to check against specific hide props (for backward compatibility)
	const actionMap: Record<string, boolean> = {
		insertImage: hideImages,
		insertVideo: hideVideos,
		insertEmbed: hideEmbeds,
		insertTable: hideTables,
		alignMenu: hideAlignment,
		textDirection: hideDirections,
		h5: hideH5H6,
		h6: hideH5H6
	}

	return actionMap[actionName] || false
}

const configToOption = (action: ToolbarConfigOption) => toolbarOptions.find(option => option.name === action) as ToolbarOption

// Helper function to check if a separator should be shown
function shouldShowSeparator(currentIndex: number): boolean {
	const allActions = config.map(configToOption).filter(Boolean)

	// Simple approach: find the last visible item before this separator
	let lastVisibleBeforeIndex = -1
	for (let i = currentIndex - 1; i >= 0; i--) {
		const action = allActions[i]
		if (action && action.name !== 'separator' && !shouldHideAction(action.name)) {
			lastVisibleBeforeIndex = i
			break
		}
	}

	// Find the first visible item after this separator
	let firstVisibleAfterIndex = -1
	for (let i = currentIndex + 1; i < allActions.length; i++) {
		const action = allActions[i]
		if (action && action.name !== 'separator' && !shouldHideAction(action.name)) {
			firstVisibleAfterIndex = i
			break
		}
	}

	// Don't show if we don't have visible items on both sides
	if (lastVisibleBeforeIndex === -1 || firstVisibleAfterIndex === -1) {
		return false
	}

	// Check if there's already a visible separator between these items
	for (let i = lastVisibleBeforeIndex + 1; i < currentIndex; i++) {
		const action = allActions[i]
		if (action && action.name === 'separator') {
			// There's already a separator closer to the visible items
			return false
		}
	}

	return true
}

function runAction(name: ToolbarConfigOption, value?: string) {
	console.log('EditorToolbar: runAction called', { name, value })
	emit('action', name, value)
}

function handleQuickTableInsert(rows: number, cols: number) {
	// Create a simple table quickly
	const table = document.createElement('table')
	table.style.width = '100%'
	table.style.borderCollapse = 'collapse'
	table.style.marginBottom = '1rem'

	// Add header
	const thead = document.createElement('thead')
	const headerRow = thead.insertRow()
	for (let j = 0; j < cols; j++) {
		const th = document.createElement('th')
		th.innerHTML = `Header ${j + 1}`
		th.style.padding = '8px'
		th.style.border = '1px solid #ddd'
		th.style.backgroundColor = '#f4f4f4'
		headerRow.appendChild(th)
	}
	table.appendChild(thead)

	// Add body
	const tbody = document.createElement('tbody')
	for (let i = 0; i < rows; i++) {
		const row = tbody.insertRow()
		for (let j = 0; j < cols; j++) {
			const cell = row.insertCell()
			cell.innerHTML = '&nbsp;'
			cell.style.padding = '8px'
			cell.style.border = '1px solid #ddd'
		}
	}
	table.appendChild(tbody)

	emit('action', 'insertTable', table.outerHTML)
}

function handleOpenAdvanced() {
	// The advanced table editor is now handled by the main RichText component
	// through the insertTable command which opens the main modal
	emit('action', 'insertTable')
}
</script>

<template>
	<div class="toolbar flex gap-025 pb-05 flex-wrap" role="toolbar" style="position: relative;">
		<template v-for="(action, index) in config.map(configToOption).filter(Boolean)" :key="index">
			<!-- Tables -->
			<TableGridSelector v-if="action.name === 'insertTable' && !shouldHideAction('insertTable')" @insert="handleQuickTableInsert" @open-advanced="handleOpenAdvanced" />
			<!-- Images -->
			<Btn
				v-else-if="action.name === 'insertImage' && !shouldHideAction('insertImage')" v-tooltip="action.label" :icon="action.icon" thin flat :aria-label="action.name"
				:class="[action.class, { active: selectedStyles.has(action.name) }]" class="" tabindex="-1" @click="runAction(action.name)"
			/>

			<!-- Videos -->
			<Btn
				v-else-if="action.name === 'insertVideo' && !shouldHideAction('insertVideo')" v-tooltip="action.label" :icon="action.icon" thin flat :aria-label="action.name"
				:class="[action.class, { active: selectedStyles.has(action.name) }]" class="" tabindex="-1" @click="runAction(action.name)"
			/>

			<!-- Embeds -->
			<Btn
				v-else-if="action.name === 'insertEmbed' && !shouldHideAction('insertEmbed')" v-tooltip="action.label" :icon="action.icon" thin flat :aria-label="action.name"
				:class="[action.class, { active: selectedStyles.has(action.name) }]" class="" tabindex="-1" @click="runAction(action.name)"
			/>

			<!-- Alignment Menu -->
			<Dropdown
				v-else-if="action.name === 'alignMenu' && !shouldHideAction('alignMenu')" placement="bottom-start" thin flat :icon="getCurrentAlignmentIcon()"
				:class="{ 'alignment-active': isAlignmentActive() }"
			>
				<template #default="{ hide }">
					<div class="flex flex-column p-025">
						<Btn thin flat icon="format_align_left" :class="{ active: selectedStyles.has('alignLeft') }" @click="runAction('alignLeft'); hide()" />
						<Btn thin flat icon="format_align_center" :class="{ active: selectedStyles.has('alignCenter') }" @click="runAction('alignCenter'); hide()" />
						<Btn thin flat icon="format_align_right" :class="{ active: selectedStyles.has('alignRight') }" @click="runAction('alignRight'); hide()" />
						<Btn thin flat icon="format_align_justify" :class="{ active: selectedStyles.has('alignJustify') }" @click="runAction('alignJustify'); hide()" />
					</div>
				</template>
			</Dropdown>

			<!-- Text Direction -->
			<Btn
				v-else-if="action.name === 'textDirection' && !shouldHideAction('textDirection')" v-tooltip="action.label"
				:icon="selectedStyles.has('textDirection') ? 'format_textdirection_l_to_r' : 'format_textdirection_r_to_l'" thin flat :aria-label="action.name"
				:class="[action.class, { active: selectedStyles.has('textDirection') }]" class="" tabindex="-1" @click="runAction(action.name)"
			/>

			<!-- H5 and H6 -->
			<Btn
				v-else-if="(action.name === 'h5' || action.name === 'h6') && !shouldHideAction(action.name)" v-tooltip="action.label" :icon="action.icon" thin flat :aria-label="action.name"
				:class="[action.class, { active: selectedStyles.has(action.name) }]" class="" tabindex="-1" @click="runAction(action.name)"
			/>

			<!-- All other buttons - check if they should be hidden by the hide array -->
			<Btn
				v-else-if="action.name !== 'separator'
					&& action.name !== 'insertTable'
					&& action.name !== 'insertImage'
					&& action.name !== 'insertVideo'
					&& action.name !== 'insertEmbed'
					&& action.name !== 'alignMenu'
					&& action.name !== 'textDirection'
					&& action.name !== 'h5'
					&& action.name !== 'h6'
					&& !shouldHideAction(action.name)" v-tooltip="action.label" :icon="action.icon" thin flat :aria-label="action.name" :class="[action.class, { active: selectedStyles.has(action.name) }]" class=""
				tabindex="-1" @click="runAction(action.name)"
			/>

			<!-- Separator -->
			<span v-else-if="action.name === 'separator' && shouldShowSeparator(index)" :key="`separator-${index}`" class="opacity-2 mb-025">|</span>
		</template>
	</div>
</template>

<style scoped>
.toolbar :deep(.active) {
	background: var(--bgl-primary);
	color: white !important;
}
.toolbar :deep(.active):hover {
	background: var(--bgl-primary) !important;
		color: white;
}
/* Headings menu styling */
.toolbar :deep(.dropdown-content) {
	min-width: 40px;
}

.toolbar :deep(.dropdown-content .btn) {
	min-width: 32px;
	height: 32px;
	padding: 0;
}
/* Alignment active state */
.alignment-active :deep(button) {
	background: var(--bgl-primary) !important;
	color: white !important;
}

.alignment-active :deep(button:hover) {
	background: var(--bgl-primary) !important;
	color: white !important;
}
</style>
