<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 type { Log } from '@/pages/admin/logs/data/schema'

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

const { t } = useI18n()

interface Application {
  id: number
  name: string
}

const loading = ref(true)
const logs = ref<Log[]>([])
const applications = ref<Application[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const appFilter = ref<string>('')
const typeFilter = ref<string>('')
const statusFilter = ref<string>('')
const startDate = ref<string>('')
const endDate = ref<string>('')

const successCount = computed(() => logs.value.filter(log => log.status === 'success').length)
const failedCount = computed(() => logs.value.filter(log => log.status === 'failed').length)
const operationCount = computed(() => logs.value.filter(log => log.log_type === 'operation').length)

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

const typeOptions = computed(() => [
  { 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.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) {
      params.append('application_id', appFilter.value)
    }
    if (typeFilter.value) {
      params.append('type', typeFilter.value)
    }
    if (statusFilter.value) {
      params.append('status', statusFilter.value)
    }
    if (startDate.value) {
      params.append('start_date', startDate.value.split('T')[0])
    }
    if (endDate.value) {
      params.append('end_date', endDate.value.split('T')[0])
    }
    
    const data = await api.get<{ logs: Log[], total: number }>(`/dev/logs?${params.toString()}`)
    logs.value = data?.logs || []
    total.value = data?.total || 0
  }
  catch (error) {
    console.error('获取日志记录失败:', error)
    logs.value = []
  }
  finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchApplications()
  fetchLogs()
})

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

const serverPagination = computed(() => ({
  currentPage: currentPage.value,
  pageSize: pageSize.value,
  total: total.value,
  onChange: (page: number) => {
    currentPage.value = page
    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">
              {{ successCount }}
            </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">
              {{ failedCount }}
            </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">
              {{ operationCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            :loading
            :data="logs"
            :server-pagination="serverPagination"
            @refresh="fetchLogs"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.logs.columns.application')"
                :options="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>
