<script setup lang="ts" generic="TData, TValue">
import { UiButton } from '@/components/UiButton';
import { UiIcon } from '@/components/UiIcon';
import { cn } from '@/lib/utils';
import { computed } from 'vue';
import { DATA_TABLE_LABELS } from './constants';
import type { UiDataTableColumnHeaderProps } from './types';

defineOptions({
  name: 'UiDataTableColumnHeader',
  // inheritAttrs: false is required here for manual class handling in conditional rendering.
  // The component renders different structures (sortable button vs plain div) and needs
  // explicit control over where $attrs.class is applied to maintain proper styling.
  // This is consistent with shadcn's approach for complex components (e.g., AlertDialogContent).
  inheritAttrs: false,
});

const props = defineProps<UiDataTableColumnHeaderProps<TData, TValue>>();

const labels = computed(() => ({
  sortedAscending:
    props.labels?.sortedAscending ?? DATA_TABLE_LABELS.sortedAscending,
  sortedDescending:
    props.labels?.sortedDescending ?? DATA_TABLE_LABELS.sortedDescending,
  clickToSort: props.labels?.clickToSort ?? DATA_TABLE_LABELS.clickToSort,
}));

const sortLabel = computed(() => {
  const sortState = props.column.getIsSorted();
  if (sortState === 'asc')
    return `${props.title}, ${labels.value.sortedAscending}`;
  if (sortState === 'desc')
    return `${props.title}, ${labels.value.sortedDescending}`;
  return `${props.title}, ${labels.value.clickToSort}`;
});

function handleSort() {
  const current = props.column.getIsSorted();
  if (current === false) {
    props.column.toggleSorting(false); // -> asc
  } else if (current === 'asc') {
    props.column.toggleSorting(true); // -> desc
  } else {
    props.column.clearSorting(); // -> unsorted
  }
}
</script>

<template>
  <div
    v-if="column.getCanSort()"
    :class="cn('flex items-center gap-x-1', $attrs.class ?? '')"
  >
    <span>{{ title }}</span>
    <UiButton
      variant="ghost"
      size="icon-sm-no-padding"
      :aria-label="sortLabel"
      @click="handleSort"
    >
      <UiIcon
        v-if="column.getIsSorted() === 'desc'"
        name="arrow-down"
        :size="16"
        aria-hidden="true"
      />
      <UiIcon
        v-else-if="column.getIsSorted() === 'asc'"
        name="arrow-up"
        :size="16"
        aria-hidden="true"
      />
      <UiIcon v-else name="chevrons-up-down" :size="16" aria-hidden="true" />
    </UiButton>
  </div>

  <div v-else :class="$attrs.class">
    {{ title }}
  </div>
</template>
