<script setup lang="ts" generic="TData">
import {
  UiDropdownMenu,
  UiDropdownMenuCheckboxItem,
  UiDropdownMenuContent,
  UiDropdownMenuTrigger,
} from '@/components/UiDropdownMenu';
import { UiIcon } from '@/components/UiIcon';
import { UiToggle } from '@/components/UiToggle';
import { computed, ref } from 'vue';
import { DATA_TABLE_LABELS } from './constants';
import type { UiDataTableColumnFilterProps } from './types';

type ColumnMetaLabel = {
  /** Human-readable label used in the column visibility menu. */
  label?: string;
};

defineOptions({
  name: 'UiDataTableColumnFilter',
});

const props = defineProps<UiDataTableColumnFilterProps<TData>>();
const isOpen = ref(false);

const labels = computed(() => ({
  columns: props.labels?.columns ?? DATA_TABLE_LABELS.columns,
  toggleColumns: props.labels?.toggleColumns ?? DATA_TABLE_LABELS.toggleColumns,
}));

const columns = computed(() =>
  props.table.getAllLeafColumns().filter((column) => column.getCanHide()),
);

function getColumnLabel(column: (typeof columns.value)[number]) {
  const metaLabel = (column.columnDef.meta as ColumnMetaLabel | undefined)
    ?.label;

  if (metaLabel) return metaLabel;
  if (typeof column.columnDef.header === 'string')
    return column.columnDef.header;

  return column.id;
}
</script>

<template>
  <UiDropdownMenu v-model:open="isOpen">
    <UiDropdownMenuTrigger as-child>
      <UiToggle
        :active="isOpen"
        variant="soft"
        size="sm"
        class="label-14-medium h-8 font-medium"
        left-icon="columns3"
        :aria-label="labels.toggleColumns"
      >
        {{ labels.columns }}
        <template #right-icon>
          <UiIcon
            name="chevron-down"
            :size="16"
            class="transition-transform"
            :class="isOpen ? 'rotate-180' : undefined"
            aria-hidden="true"
          />
        </template>
      </UiToggle>
    </UiDropdownMenuTrigger>
    <UiDropdownMenuContent align="end" class="flex flex-col gap-2 p-2">
      <UiDropdownMenuCheckboxItem
        v-for="column in columns"
        :key="column.id"
        :checked="column.getIsVisible()"
        :text-value="getColumnLabel(column)"
        class="body-14-regular gap-2 p-2 pl-8 font-normal"
        @update:checked="column.toggleVisibility($event)"
      >
        {{ getColumnLabel(column) }}
      </UiDropdownMenuCheckboxItem>
    </UiDropdownMenuContent>
  </UiDropdownMenu>
</template>
