<script setup lang="ts">
import { useLogsView } from './composables/useLogsView'

const {
  Terminal,
  RefreshCw,
  Bot,
  MessageSquare,
  Settings,
  AlertCircle,
  ChevronDown,
  ChevronRight,
  logs,
  stats,
  loading,
  errorMessage,
  expandedLogId,
  autoRefresh,
  filters,
  total,
  totalPages,
  visiblePageNumbers,
  timePresets,
  logTypes,
  logLevels,
  statusCodeOptions,
  levelColors,
  typeLabels,
  formatTime,
  formatDuration,
  formatDetails,
  toggleDetails,
  applyPreset,
  markCustomRange,
  toggleAutoRefresh,
  applyFilters,
  resetFilters,
  goToPage,
  prevPage,
  nextPage,
  changePageSize,
  loadData,
} = useLogsView()
</script>

<template>
  <div class="log-view">
    <div class="view-header">
      <div class="header-title">
        <Terminal :size="16" />
        <span>运行日志</span>
      </div>
      <div class="header-actions">
        <button class="btn-icon" :class="{ active: autoRefresh }" @click="toggleAutoRefresh" title="自动刷新">
          <RefreshCw :size="14" :class="{ spinning: autoRefresh }" />
        </button>
        <button class="btn-icon" @click="loadData" title="刷新">
          <RefreshCw :size="14" />
        </button>
      </div>
    </div>

    <div v-if="stats" class="stats-overview">
      <div class="stat-card">
        <div class="stat-label">总计</div>
        <div class="stat-value">{{ stats.total }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">智能体</div>
        <div class="stat-value cyan">{{ stats.by_type.agent }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">系统</div>
        <div class="stat-value purple">{{ stats.by_type.system }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">问答</div>
        <div class="stat-value amber">{{ stats.by_type.chat }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">错误</div>
        <div class="stat-value red">{{ stats.by_level.error }}</div>
      </div>
    </div>

    <div class="filters">
      <div class="toolbar-row presets-row">
        <button
          v-for="preset in timePresets"
          :key="preset.value"
          class="filter-btn"
          :class="{ active: filters.preset === preset.value }"
          @click="applyPreset(preset.value)"
        >
          {{ preset.label }}
        </button>
      </div>

      <div class="toolbar-row fields-row">
        <input v-model="filters.start_at" class="filter-input" type="datetime-local" @input="markCustomRange" />
        <input v-model="filters.end_at" class="filter-input" type="datetime-local" @input="markCustomRange" />
        <input v-model="filters.request_id" class="filter-input" type="text" placeholder="Request ID" />
        <input v-model="filters.route" class="filter-input" type="text" placeholder="Route" />
        <input v-model="filters.operation" class="filter-input" type="text" placeholder="Operation" />
        <select v-model="filters.status_code" class="filter-select">
          <option v-for="option in statusCodeOptions" :key="option.label" :value="option.value">{{ option.label }}</option>
        </select>
        <select v-model="filters.log_type" class="filter-select">
          <option v-for="option in logTypes" :key="option.label" :value="option.value">{{ option.label }}</option>
        </select>
        <select v-model="filters.level" class="filter-select">
          <option v-for="option in logLevels" :key="option.label" :value="option.value">{{ option.label }}</option>
        </select>
        <button class="action-btn primary" @click="applyFilters">查询</button>
        <button class="action-btn" @click="resetFilters">重置</button>
      </div>
    </div>

    <div class="log-list">
      <div v-if="loading && logs.length === 0" class="loading-state">
        <RefreshCw :size="20" class="spinning" />
        <span>加载中...</span>
      </div>

      <div v-else-if="errorMessage" class="empty-state error-state">
        <AlertCircle :size="32" />
        <span>{{ errorMessage }}</span>
      </div>

      <div v-else-if="logs.length === 0" class="empty-state">
        <Terminal :size="32" />
        <span>暂无日志</span>
      </div>

      <div v-else class="log-items">
        <div v-for="log in logs" :key="log.id" class="log-item">
          <div class="log-summary" @click="toggleDetails(log.id)">
            <div class="log-meta">
              <span class="log-type" :class="log.type">{{ typeLabels[log.type] || log.type }}</span>
              <span class="log-level" :style="{ color: levelColors[log.level] }">{{ log.level }}</span>
              <span v-if="log.duration_ms !== null" class="log-duration">{{ formatDuration(log.duration_ms) }}</span>
              <span v-if="log.status_code" class="log-status">HTTP {{ log.status_code }}</span>
            </div>
            <div class="log-message">{{ log.message }}</div>
            <div class="log-footer">
              <span v-if="log.source" class="log-source">{{ log.source }}</span>
              <span v-if="log.operation" class="log-operation">{{ log.operation }}</span>
              <span class="log-time">{{ formatTime(log.created_at) }}</span>
              <span class="log-expand">
                <ChevronDown v-if="expandedLogId === log.id" :size="14" />
                <ChevronRight v-else :size="14" />
              </span>
            </div>
          </div>
          <div v-if="expandedLogId === log.id" class="log-details">
            <div v-if="log.request_id" class="detail-row"><strong>Request ID:</strong> {{ log.request_id }}</div>
            <div v-if="log.route || log.method" class="detail-row"><strong>Route:</strong> {{ log.method || '-' }} {{ log.route || '-' }}</div>
            <div v-if="log.error_type" class="detail-row"><strong>Error:</strong> {{ log.error_type }}</div>
            <pre v-if="log.details" class="detail-json">{{ formatDetails(log.details) }}</pre>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination">
      <div class="page-summary">共 {{ total }} 条 · 第 {{ filters.page }} / {{ totalPages }} 页</div>
      <div class="page-controls">
        <button class="page-btn" :disabled="filters.page === 1" @click="prevPage">上一页</button>
        <button
          v-for="page in visiblePageNumbers"
          :key="page"
          class="page-btn page-number"
          :class="{ active: page === filters.page }"
          @click="goToPage(page)"
        >
          {{ page }}
        </button>
        <button class="page-btn" :disabled="filters.page >= totalPages" @click="nextPage">下一页</button>
        <select class="filter-select page-size-select" :value="filters.page_size" @change="changePageSize(Number(($event.target as HTMLSelectElement).value))">
          <option v-for="size in [20, 50, 100]" :key="size" :value="size">{{ size }}/页</option>
        </select>
      </div>
    </div>
  </div>
</template>

<style scoped src="./logsPage.css"></style>
