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

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

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

const { t } = useI18n()

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

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

const columnLabels: Record<string, string> = {
  select: 'agent.finance.select',
  type: 'agent.finance.columns.type',
  description: 'agent.finance.columns.description',
  amount: 'agent.finance.columns.amount',
  balance: 'agent.finance.columns.balance',
  created_at: 'agent.finance.columns.createdAt',
}

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
              :type-filter="typeFilter"
              @update:typeFilter="emit('update:typeFilter', $event)"
            />
            <slot name="filters" />
          </div>
          <DataTableViewOptions :table="table" :column-labels="columnLabels" />
        </div>
      </div>
    </template>
  </DataTable>
</template>
