<script setup lang="ts" generic="T">
import type { Table } from '@tanstack/vue-table'

import { RefreshCcw, Settings2 } from 'lucide-vue-next'
import { useI18n } from 'vue-i18n'

interface DataTableViewOptionsProps {
  table: Table<T>
  columnLabels?: Record<string, string>
}

const props = defineProps<DataTableViewOptionsProps>()
const { t } = useI18n()

const columns = computed(() => props.table.getAllColumns()
  .filter(
    column =>
      typeof column.accessorFn !== 'undefined' && column.getCanHide(),
  ))

function resetColumnVisible() {
  columns.value.forEach(column => column.toggleVisibility(true))
}

function getColumnLabel(columnId: string): string {
  if (props.columnLabels && props.columnLabels[columnId]) {
    try {
      return t(props.columnLabels[columnId])
    }
    catch {
      return columnId
    }
  }
  return columnId
}
</script>

<template>
  <UiDropdownMenu>
    <UiDropdownMenuTrigger as-child>
      <UiButton
        variant="outline"
        size="sm"
        class="hidden h-8 ml-auto lg:flex"
      >
        <Settings2 class="size-4 mr-2" />
        {{ t('common.columnsView') }}
      </UiButton>
    </UiDropdownMenuTrigger>
    <UiDropdownMenuContent align="end" class="w-[150px]">
      <UiDropdownMenuLabel>{{ t('common.toggleColumns') }}</UiDropdownMenuLabel>
      <UiDropdownMenuSeparator />

      <UiDropdownMenuCheckboxItem
        v-for="column in columns"
        :key="column.id"
        :model-value="column.getIsVisible()"
        @update:model-value="(value:boolean) => column.toggleVisibility(!!value)"
      >
        {{ getColumnLabel(column.id) }}
      </UiDropdownMenuCheckboxItem>

      <UiDropdownMenuSeparator />
      <UiDropdownMenuItem
        @click="resetColumnVisible"
      >
        <RefreshCcw class="mr-2 h-4 w-4" />
        {{ t('common.reset') }}
      </UiDropdownMenuItem>
    </UiDropdownMenuContent>
  </UiDropdownMenu>
</template>
