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

import { computed } from 'vue'

import type { DataTableProps } from '@/components/data-table/types'
import type { EmailConfig } from '@/pages/admin/email-settings/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/email-settings/components/columns'

const props = defineProps<Omit<DataTableProps<EmailConfig>, 'columns'> & {
  onToggleStatus: (row: EmailConfig) => void
  onEdit: (row: EmailConfig) => void
  onDelete: (row: EmailConfig) => void
  onTest: (row: EmailConfig) => void
}>()

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

const t = (key: string) => key

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

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

const columnLabels: Record<string, string> = {
  select: '选择',
  name: '配置名称',
  smtp_host: 'SMTP服务器',
  smtp_user: '用户名',
  smtp_from: '发件人',
  status: '状态',
  created_at: '创建时间',
}

defineExpose({
  table,
})
</script>

<template>
  <DataTable :columns="columns" :data :loading :table @refresh="emit('refresh')">
    <template #toolbar>
      <div class="space-y-3">
        <BulkActions :table="table" entity-name="email-configs">
          <UiButton variant="outline" size="sm" @click="emit('batchEnable')">
            批量启用
          </UiButton>
          <UiButton variant="outline" size="sm" @click="emit('batchDisable')">
            批量禁用
          </UiButton>
          <UiButton variant="destructive" size="sm" @click="emit('batchDelete')">
            批量删除
          </UiButton>
        </BulkActions>
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div class="text-sm text-muted-foreground">
            共 {{ data.length }} 个邮箱配置
          </div>
          <DataTableViewOptions :table="table" :column-labels="columnLabels" />
        </div>
      </div>
    </template>
  </DataTable>
</template>
