<script setup lang="ts">
import { Activity, CheckCircle, FileText, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref } 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 appFilter = ref<string>('')
const typeFilter = ref<string>('')
const statusFilter = ref<string>('')
const startDate = ref<string>('')
const endDate = ref<string>('')

const filteredLogs = computed(() => {
  let result = logs.value

  if (appFilter.value) {
    result = result.filter(log => String(log.application_id) === appFilter.value)
  }

  if (typeFilter.value) {
    result = result.filter(log => log.log_type === typeFilter.value)
  }

  if (statusFilter.value) {
    result = result.filter(log => log.status === statusFilter.value)
  }

  if (startDate.value) {
    const fromDateTime = startDate.value.includes('T')
      ? startDate.value.replace('T', ' ')
      : `${startDate.value} 00:00`
    result = result.filter(log => log.created_at >= fromDateTime)
  }

  if (endDate.value) {
    const toDateTime = endDate.value.includes('T')
      ? endDate.value.replace('T', ' ')
      : `${endDate.value} 23:59`
    result = result.filter(log => log.created_at <= toDateTime)
  }

  return result
})

const successCount = computed(() => filteredLogs.value.filter(log => log.status === 'success').length)
const failedCount = computed(() => filteredLogs.value.filter(log => log.status === 'failed').length)
const operationCount = computed(() => filteredLogs.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 data = await api.get<{ logs: Log[] }>('/dev/logs')
    logs.value = data?.logs || []
  }
  catch (error) {
    console.error('获取日志记录失败:', error)
    logs.value = []
  }
  finally {
    loading.value = false
  }
}

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">
              {{ filteredLogs.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.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="filteredLogs"
            @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>
