<script lang="ts" setup>
import { BlitzField } from 'blitzar'
import { BlitzColumn, ROW_SELECTION_ID, SortState } from '@blitzar/types'
import { computed } from 'vue'

const props = defineProps<{
  /**
   * The BlitzField object used for the columns
   */
  column: BlitzColumn
  /**
   * Currently only compatible with 1 column sorted
   */
  sortState: SortState
}>()

const emit = defineEmits<{
  (e: 'update:sortState', payload: SortState): void
}>()

function onClick(e: MouseEvent) {
  const { id, sortable } = props.column
  if (!sortable || !id) return

  e.stopPropagation()

  if (props.sortState[0]?.id !== id) {
    return emit('update:sortState', [{ id, direction: 'asc' }])
  }
  if (props.sortState[0]?.id === id) {
    if (props.sortState[0]?.direction === 'asc') {
      return emit('update:sortState', [{ id, direction: 'desc' }])
    } else {
      return emit('update:sortState', [])
    }
  }
}

const isSelectionCol = computed(() => props.column.id === ROW_SELECTION_ID)
</script>

<template>
  <th :class="`_admin_th ${column.sortable ? '_sortable' : ''}`" @click="(e) => onClick(e)">
    <BlitzField v-if="isSelectionCol" v-bind="column" :label="undefined" />

    <div class="_wrapper">
      <div class="_label">{{ column.label }}</div>
      <template v-if="column.sortable && sortState[0]?.id === column.id">
        <template v-if="sortState[0]?.direction === 'desc'">
          <div class="_arrow _active">↑</div>
          <div class="_arrow">↓</div>
        </template>
        <template v-if="sortState[0]?.direction === 'asc'">
          <div class="_arrow">↑</div>
          <div class="_arrow _active">↓</div>
        </template>
      </template>
      <template v-else-if="column.sortable">
        <div class="_arrow">↑</div>
        <div class="_arrow">↓</div>
      </template>
    </div>
  </th>
</template>

<style lang="sass" scoped>
._admin_th
  cursor: auto
  &._sortable
    cursor: ns-resize
    user-select: none
  ._wrapper
    display: flex
  ._label
    padding-right: 0.5rem
  ._arrow
    color: lightgrey
  ._active
    color: black
</style>
