import type { Ref, ComputedRef } from 'vue'
import type { ColumnConfig, Row } from '../types'
import { ref, nextTick } from 'vue'

export function useSpreadsheetSort(
	localRows: Ref<Row[]>,
	columns: ComputedRef<ColumnConfig[]>,
	visibleColumns: Ref<string[]>,
	emitUpdate: () => void,
) {
	const sortColumn = ref<string | null>(null)
	const sortDirection = ref<'asc' | 'desc'>('asc')

	function sortByColumn(columnKey: string) {
		const column = columns.value.find(col => col.key === columnKey)
		if (!column?.sortable) { return }

		if (sortColumn.value === columnKey) {
			sortDirection.value = sortDirection.value === 'desc' ? 'asc' : 'desc'
		} else {
			sortColumn.value = columnKey
			sortDirection.value = 'desc'
		}

		const sorted = [...localRows.value].sort((a, b) => {
			const aVal = a[columnKey]
			const bVal = b[columnKey]
			if (aVal === bVal) { return 0 }
			if (aVal == null) { return 1 }
			if (bVal == null) { return -1 }
			const modifier = sortDirection.value === 'desc' ? 1 : -1
			return aVal < bVal ? -modifier : modifier
		})

		const savedVisible = [...visibleColumns.value]
		localRows.value = sorted
		emitUpdate()
		nextTick(() => { visibleColumns.value = savedVisible })
	}

	return { sortColumn, sortDirection, sortByColumn }
}
