<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 { Ticket } from '@/pages/admin/tickets/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/admin/tickets/components/columns'
import DataTableToolbar from '@/pages/admin/tickets/components/data-table-toolbar.vue'

const props = defineProps<Omit<DataTableProps<Ticket>, 'columns'> & {
  onUpdateStatus: (row: Ticket, status: string) => void
  onViewDetail: (row: Ticket) => void
  onDelete: (row: Ticket) => void
}>()

const emit = defineEmits<{
  refresh: []
  batchDelete: []
}>()

const { t } = useI18n()

const columns = computed(() => [
  SelectColumn as ColumnDef<Ticket>,
  ...getColumns({
    onUpdateStatus: props.onUpdateStatus,
    onViewDetail: props.onViewDetail,
    onDelete: props.onDelete,
  }, t),
])

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

const columnLabels: Record<string, string> = {
  select: 'admin.tickets.select',
  type: 'admin.tickets.columns.ticketType',
  title: 'admin.tickets.columns.title',
  priority: 'admin.tickets.columns.priority',
  status: 'admin.tickets.columns.status',
  app_name: 'admin.tickets.columns.application',
  user_name: 'admin.tickets.columns.submitter',
  created_at: 'admin.tickets.columns.createdAt',
  updated_at: 'admin.tickets.columns.updatedAt',
}

defineExpose({
  table,
})
</script>

<template>
  <DataTable :columns="columns" :data :loading :table @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="tickets">
          <UiButton variant="destructive" size="sm" @click="emit('batchDelete')">
            {{ t('admin.tickets.batchDeleteBtn') }}
          </UiButton>
        </BulkActions>
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div class="flex flex-wrap items-center gap-2">
            <DataTableToolbar :table />
            <slot name="filters" />
          </div>
          <DataTableViewOptions :table="table" :column-labels="columnLabels" />
        </div>
      </div>
    </template>
  </DataTable>
</template>
