<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 { App } from '@/pages/admin/applications/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/admin/applications/components/columns'

const props = defineProps<Omit<DataTableProps<App>, 'columns'> & {
  searchFilter?: string
}>()

const emit = defineEmits<{
  'refresh': []
  'goToSettings': [app: App]
  'goToSecurity': [app: App]
  'toggleStatus': [app: App]
  'delete': [app: App]
  'update:searchFilter': [value: string]
}>()

const { t } = useI18n()

const columns = computed(() => [
  SelectColumn as ColumnDef<App>,
  ...getColumns({
    onGoToSettings: (app: App) => emit('goToSettings', app),
    onGoToSecurity: (app: App) => emit('goToSecurity', app),
    onToggleStatus: (app: App) => emit('toggleStatus', app),
    onDelete: (app: App) => emit('delete', app),
  }, t),
])

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

const columnLabels: Record<string, string> = {
  select: 'admin.applications.select',
  name: 'admin.applications.columns.name',
  app_key: 'admin.applications.columns.appKey',
  billing_type: 'admin.applications.columns.billingType',
  login_policy: 'admin.applications.columns.loginPolicy',
  enable_trial: 'admin.applications.columns.trial',
  status: 'admin.applications.columns.status',
  created_at: 'admin.applications.columns.createdAt',
}

defineExpose({
  table,
})
</script>

<template>
  <DataTable :columns="columns" :data :loading :table @refresh="emit('refresh')">
    <template #toolbar>
      <div class="flex flex-wrap items-center justify-between gap-2">
        <div class="flex flex-wrap items-center gap-2">
          <UiInput
            :model-value="searchFilter"
            :placeholder="t('admin.applications.searchPlaceholder')"
            class="h-9 w-40 lg:w-[250px]"
            @update:model-value="emit('update:searchFilter', String($event))"
          />
        </div>
        <DataTableViewOptions :table="table" :column-labels="columnLabels" />
      </div>
    </template>
  </DataTable>
</template>
