import { ref, computed } from 'vue'

export function useTableSort<T extends Record<string, any>>(data: () => T[]) {
  const sortColumn = ref<string | null>(null)
  const sortDirection = ref<'asc' | 'desc'>('asc')

  function toggleSort(column: string) {
    if (sortColumn.value === column) {
      sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
    } else {
      sortColumn.value = column
      sortDirection.value = 'asc'
    }
  }

  const sorted = computed(() => {
    const items = [...data()]
    if (!sortColumn.value) return items

    const col = sortColumn.value
    const dir = sortDirection.value === 'asc' ? 1 : -1

    return items.sort((a, b) => {
      const va = a[col]
      const vb = b[col]
      if (va == null && vb == null) return 0
      if (va == null) return dir
      if (vb == null) return -dir
      if (typeof va === 'number' && typeof vb === 'number') return (va - vb) * dir
      return String(va).localeCompare(String(vb)) * dir
    })
  })

  return { sortColumn, sortDirection, toggleSort, sorted }
}
