<script setup lang="ts">
import { Activity, CheckCircle, FileText, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

import { BasicPage } from '@/components/global-layout'
import SingleFilter from '@/components/data-table/single-filter.vue'
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
import api from '@/services/api'

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

import DataTable from '@/pages/admin/logs/components/data-table.vue'

const { t } = useI18n()

interface Application {
  id: number
  name: string
}

interface LogsResponse {
  logs: Log[]
  total: number
  page: number
  page_size: number
  total_page: number
}

const loading = ref(true)
const logs = ref<Log[]>([])
const applications = ref<Application[]>([])

const appFilter = ref<string>('all')
const typeFilter = ref<string>('all')
const statusFilter = ref<string>('all')
const startDate = ref<string>('')
const endDate = ref<string>('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const totalPages = ref(0)

const applicationOptions = computed(() => {
  return applications.value.map(app => ({
    label: app.name,
    value: String(app.id),
  }))
})

const typeOptions = computed(() => [
  { label: t('admin.logs.types.all'), value: 'all' },
  { label: t('admin.logs.types.operation'), value: 'operation' },
  { label: t('admin.logs.types.verification'), value: 'verification' },
  { label: t('admin.logs.types.exception'), value: 'exception' },
])

const statusOptions = computed(() => [
  { label: t('admin.logs.statuses.all'), value: 'all' },
  { label: t('admin.success'), value: 'success' },
  { label: t('admin.failed'), value: 'failed' },
])

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

async function fetchLogs() {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', String(currentPage.value))
    params.append('page_size', String(pageSize.value))
    
    if (appFilter.value && appFilter.value !== 'all') {
      params.append('application_id', appFilter.value)
    }
    if (typeFilter.value && typeFilter.value !== 'all') {
      params.append('type', typeFilter.value)
    }
    if (statusFilter.value && statusFilter.value !== 'all') {
      params.append('status', statusFilter.value)
    }
    if (startDate.value) {
      params.append('start_date', startDate.value)
    }
    if (endDate.value) {
      params.append('end_date', endDate.value)
    }

    const data = await api.get<LogsResponse>(`/dev/logs?${params.toString()}`)
    
    if (data) {
      logs.value = data.logs || []
      total.value = data.total || 0
      currentPage.value = data.page || 1
      totalPages.value = data.total_page || 0
    }
  }
  catch (error) {
    console.error('获取日志记录失败:', error)
    logs.value = []
  }
  finally {
    loading.value = false
  }
}

watch([appFilter, typeFilter, statusFilter, startDate, endDate], () => {
  currentPage.value = 1
  fetchLogs()
})

onMounted(() => {
  fetchApplications()
  fetchLogs()
})
</script>

<template>
  <BasicPage
    :title="t('admin.logs.title')"
    :description="t('admin.logs.description')"
    sticky
  >
    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.logs.totalLogs') }}
            </UiCardTitle>
            <FileText class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ total }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.logs.successCount') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ logs.filter(log => log.status === 'success').length }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.logs.failedCount') }}
            </UiCardTitle>
            <XCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ logs.filter(log => log.status === 'failed').length }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.logs.operationCount') }}
            </UiCardTitle>
            <Activity class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ logs.filter(log => log.log_type === 'operation').length }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="logs"
            :server-page="currentPage"
            :server-page-size="pageSize"
            :server-total="total"
            :server-total-pages="totalPages"
            @refresh="fetchLogs"
            @page-change="currentPage = $event; fetchLogs()"
            @page-size-change="pageSize = $event; currentPage = 1; fetchLogs()"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.logs.columns.application')"
                :options="[{ label: t('admin.logs.allApplications'), value: 'all' }, ...applicationOptions]"
              />
              <SingleFilter
                v-model="typeFilter"
                :title="t('admin.logs.columns.type')"
                :options="typeOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.logs.columns.status')"
                :options="statusOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="startDate"
                v-model:end-model-value="endDate"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>
  </BasicPage>
</template>
