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

import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

import type { DataTableProps } from '@/components/data-table/types'
import type { Card } from '@/pages/agent/cards/data/schema'

import BulkActions from '@/components/data-table/bulk-actions.vue'
import DataTable from '@/components/data-table/data-table.vue'
import { SelectColumn } from '@/components/data-table/table-columns'
import { generateVueTable } from '@/components/data-table/use-generate-vue-table'
import DataTableViewOptions from '@/components/data-table/view-options.vue'
import { getColumns } from '@/pages/agent/cards/components/columns'
import DataTableToolbar from '@/pages/agent/cards/components/data-table-toolbar.vue'

const props = defineProps<Omit<DataTableProps<Card>, 'columns'> & {
  searchFilter?: string
  serverPagination?: DataTableProps<Card>['serverPagination']
}>()

const emit = defineEmits<{
  'refresh': []
  'batchExport': []
  'export': []
  'update:searchFilter': [value: string]
}>()

const { t } = useI18n()

const columns = computed(() => [
  SelectColumn as ColumnDef<Card>,
  ...getColumns(t),
])

const table = generateVueTable<Card>({
  get data() { return props.data },
  get loading() { return props.loading },
  columns: columns.value,
  serverPagination: props.serverPagination,
})

const columnLabels: Record<string, string> = {
  select: 'agent.cards.select',
  code: 'agent.cards.columns.code',
  app_name: 'agent.cards.columns.appName',
  card_type_name: 'agent.cards.columns.cardTypeName',
  status: 'agent.cards.columns.status',
  created_at: 'agent.cards.columns.createdAt',
  used_at: 'agent.cards.columns.usedAt',
}

defineExpose({
  table,
})
</script>

<template>
  <DataTable :columns="columns" :data :loading :table :server-pagination @refresh="emit('refresh')">
    <template #toolbar>
      <div class="space-y-3">
        <div class="flex items-center justify-end">
          <slot name="actions" />
        </div>
        <BulkActions :table="table" entity-name="cards">
          <UiButton variant="outline" size="sm" @click="emit('batchExport')">
            {{ t('agent.cards.batchExportBtn') }}
          </UiButton>
        </BulkActions>
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div class="flex flex-wrap items-center gap-2">
            <DataTableToolbar
              :table
              :search-filter="searchFilter"
              @update:search-filter="emit('update:searchFilter', $event)"
            />
            <slot name="filters" />
          </div>
          <div class="flex items-center gap-2">
            <UiButton variant="outline" size="sm" @click="emit('export')">
              {{ t('agent.cards.exportBtn') }}
            </UiButton>
            <DataTableViewOptions :table="table" :column-labels="columnLabels" />
          </div>
        </div>
      </div>
    </template>
  </DataTable>
</template>
