<script setup lang="ts">
import { Btn, Dropdown } from '@bagelink/vue'
import { ref, computed } from 'vue'

const emit = defineEmits<{
	insert: [rows: number, cols: number]
	openAdvanced: []
}>()

const hoveredRow = ref(0)
const hoveredCol = ref(0)

const maxRows = 10
const maxCols = 10

const gridCells = computed(() => {
	const cells = []
	for (let row = 1; row <= maxRows; row++) {
		for (let col = 1; col <= maxCols; col++) {
			cells.push({
				row,
				col,
				isActive: row <= hoveredRow.value && col <= hoveredCol.value
			})
		}
	}
	return cells
})

const selectionText = computed(() => {
	if (hoveredRow.value === 0 || hoveredCol.value === 0) {
		return 'Select table size'
	}
	return `${hoveredRow.value} × ${hoveredCol.value}`
})

function handleCellHover(row: number, col: number) {
	hoveredRow.value = row
	hoveredCol.value = col
}

function handleCellClick(row: number, col: number, hide: () => void) {
	emit('insert', row, col)
	hide()
}

function handleAdvanced(hide: () => void) {
	emit('openAdvanced')
	hide()
}

function handleMouseLeave() {
	hoveredRow.value = 0
	hoveredCol.value = 0
}
</script>

<template>
	<Dropdown placement="bottom-start" thin flat icon="table">
		<template #default="{ hide }">
			<div class="table-grid-selector p-075">
				<!-- Header -->
				<div class="txt-center mb-075">
					<div style="font-size: 14px; font-weight: 500; color: #333; margin-bottom: 4px;">
						{{ selectionText }}
					</div>
					<div style="font-size: 12px; color: #666;">
						Hover to select size
					</div>
				</div>

				<!-- Grid -->
				<div style="display: grid; grid-template-columns: repeat(10, 20px); grid-template-rows: repeat(10, 20px); gap: 2px; margin-bottom: 12px; direction: ltr;" @mouseleave="handleMouseLeave" @blur="handleMouseLeave">
					<div
						v-for="cell in gridCells" :key="`${cell.row}-${cell.col}`" tabindex="0" :style="{
							width: '20px',
							height: '20px',
							border: '1px solid var(--bgl-border-color)',
							backgroundColor: cell.isActive ? 'var(--bgl-primary)' : 'var(--bgl-input-bg)',
							cursor: 'pointer',
							borderRadius: '2px',
							transition: 'background-color 0.1s ease',
						}" @focus="handleCellHover(cell.row, cell.col)" @mouseenter="handleCellHover(cell.row, cell.col)" @click="handleCellClick(cell.row, cell.col, hide)"
					/>
				</div>

				<!-- Advanced button -->
				<div class="border-top pt-075">
					<Btn value="Advanced Settings" icon="settings" class="bg-gray-30 color-black" @click="handleAdvanced(hide)" />
				</div>
			</div>
		</template>
	</Dropdown>
</template>
