<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

import type { ColumnDef } from '@tanstack/vue-table'

import DataTable from '@/components/data-table/data-table.vue'
import { generateVueTable } from '@/components/data-table/use-generate-vue-table'
import { SelectColumn } from '@/components/data-table/table-columns'
import DataTableViewOptions from '@/components/data-table/view-options.vue'

import type { Log } from '@/pages/admin/logs/data/schema'

import { getColumns } from '@/pages/admin/logs/components/columns'
import DataTableToolbar from '@/pages/admin/logs/components/data-table-toolbar.vue'

const { t } = useI18n()

interface Props {
  loading?: boolean
  data: Log[]
  serverPage?: number
  serverPageSize?: number
  serverTotal?: number
  serverTotalPages?: number
}

const props = defineProps<Props>()
const emit = defineEmits<{
  refresh: []
  'page-change': [page: number]
  'page-size-change': [pageSize: number]
}>()

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

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

const columnLabels: Record<string, string> = {
  'select': 'admin.logs.select',
  'type': 'admin.logs.columns.type',
  'action': 'admin.logs.columns.action',
  'details': 'admin.logs.columns.detail',
  'status': 'admin.logs.columns.status',
  'ip': 'admin.logs.columns.ip',
  'application_name': 'admin.logs.columns.application',
  'user_username': 'admin.logs.columns.user',
  'created_at': 'admin.logs.columns.time',
}

const serverPagination = computed(() => {
  if (props.serverPage && props.serverPageSize && props.serverTotal) {
    return {
      page: props.serverPage,
      pageSize: props.serverPageSize,
      total: props.serverTotal,
      onPageChange: (page: number) => emit('page-change', page),
      onPageSizeChange: (pageSize: number) => emit('page-size-change', pageSize),
    }
  }
  return undefined
})

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>
        <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>
