import type { ComputedRef } from 'vue'
import type { CellPosition, ColumnConfig } from '../types'
import { ref, onUnmounted } from 'vue'

export function useSpreadsheetSelection(columns: ComputedRef<ColumnConfig[]>) {
	const isSelecting = ref(false)
	const selectionStart = ref<CellPosition | null>(null)
	const selectionEnd = ref<CellPosition | null>(null)

	function handleMouseDown(row: number, col: number) {
		selectionStart.value = { row, col }
		selectionEnd.value = { row, col }
		isSelecting.value = true
	}

	function handleMouseOver(row: number, col: number) {
		if (isSelecting.value) {
			selectionEnd.value = { row, col }
		}
	}

	function handleMouseUp() {
		isSelecting.value = false
	}

	function selectEntireRow(rowIndex: number) {
		selectionStart.value = { row: rowIndex, col: 0 }
		selectionEnd.value = { row: rowIndex, col: columns.value.length - 1 }
	}

	window.addEventListener('mouseup', handleMouseUp)
	onUnmounted(() => { window.removeEventListener('mouseup', handleMouseUp) })

	return {
		isSelecting,
		selectionStart,
		selectionEnd,
		handleMouseDown,
		handleMouseOver,
		handleMouseUp,
		selectEntireRow,
	}
}
