<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 { User } from '@/pages/agent/users/data/schema'

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/users/components/columns'
import DataTableToolbar from '@/pages/agent/users/components/data-table-toolbar.vue'

const props = defineProps<Omit<DataTableProps<User>, 'columns'> & {
  searchFilter?: string
  serverPagination?: DataTableProps<User>['serverPagination']
  onEdit: (row: User) => void
  onToggleStatus: (row: User) => void
}>()

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

const { t } = useI18n()

const columns = computed(() => [
  SelectColumn as ColumnDef<User>,
  ...getColumns({
    onEdit: props.onEdit,
    onToggleStatus: props.onToggleStatus,
  }, t),
])

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

const columnLabels: Record<string, string> = {
  select: 'agent.users.select',
  username: 'agent.users.columns.username',
  email: 'agent.users.columns.email',
  status: 'agent.users.columns.status',
  created_at: 'agent.users.columns.createdAt',
  last_login_at: 'agent.users.columns.lastLoginAt',
}

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 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>
          <DataTableViewOptions :table="table" :column-labels="columnLabels" />
        </div>
      </div>
    </template>
  </DataTable>
</template>
