<template>
  <div class="admin-view">
    <!-- 頁面標題 -->
    <div class="page-header">
      <h1 class="page-title">管理後台</h1>
      <div class="page-actions">
        <el-dropdown @command="handleExportCommand">
          <el-button>
            <el-icon><Download /></el-icon>
            匯出報表
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="usage">使用統計報表</el-dropdown-item>
              <el-dropdown-item command="cost">成本分析報表</el-dropdown-item>
              <el-dropdown-item command="jobs">任務清單報表</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-button @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新資料
        </el-button>
      </div>
    </div>

    <!-- 系統概覽 -->
    <div class="overview-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon primary">
            <el-icon><DataBoard /></el-icon>
          </div>
          <div class="stat-value">{{ overviewStats.total_jobs || 0 }}</div>
          <div class="stat-label">總任務數</div>
          <div class="stat-change positive" v-if="dailyStats.length > 0">
            +{{ dailyStats[dailyStats.length - 1]?.jobs || 0 }} 今日
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon success">
            <el-icon><SuccessFilled /></el-icon>
          </div>
          <div class="stat-value">{{ overviewStats.completed_jobs || 0 }}</div>
          <div class="stat-label">已完成</div>
          <div class="stat-change positive" v-if="dailyStats.length > 0">
            +{{ dailyStats[dailyStats.length - 1]?.completed || 0 }} 今日
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon warning">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-value">{{ overviewStats.active_users_today || 0 }}</div>
          <div class="stat-label">今日活躍用戶</div>
          <div class="stat-total">總用戶: {{ overviewStats.total_users || 0 }}</div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon info">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-value">${{ (overviewStats.total_cost || 0).toFixed(4) }}</div>
          <div class="stat-label">總成本</div>
          <div class="stat-change positive" v-if="dailyStats.length > 0">
            +${{ (dailyStats[dailyStats.length - 1]?.cost || 0).toFixed(4) }} 今日
          </div>
        </div>
      </div>
    </div>

    <!-- 圖表區域 -->
    <div class="charts-section">
      <div class="chart-row">
        <!-- 每日任務統計圖表 -->
        <div class="content-card chart-card">
          <div class="card-header">
            <h3 class="card-title">每日任務統計</h3>
            <div class="card-actions">
              <el-select v-model="chartPeriod" @change="handlePeriodChange" size="small">
                <el-option label="最近 7 天" value="week" />
                <el-option label="最近 30 天" value="month" />
                <el-option label="最近 90 天" value="quarter" />
              </el-select>
            </div>
          </div>
          <div class="card-body">
            <div ref="dailyChartRef" class="chart-container"></div>
          </div>
        </div>
        
        <!-- 成本趨勢圖表 -->
        <div class="content-card chart-card">
          <div class="card-header">
            <h3 class="card-title">成本趨勢</h3>
          </div>
          <div class="card-body">
            <div ref="costChartRef" class="chart-container"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用戶排行與系統狀態 -->
    <div class="info-section">
      <div class="info-row">
        <!-- 用戶使用排行 -->
        <div class="content-card">
          <div class="card-header">
            <h3 class="card-title">用戶使用排行</h3>
          </div>
          <div class="card-body">
            <div v-if="loading" class="loading-state">
              <el-skeleton :rows="5" animated />
            </div>
            <div v-else-if="userRankings.length === 0" class="empty-state">
              <el-icon class="empty-icon"><User /></el-icon>
              <div class="empty-title">暫無用戶資料</div>
            </div>
            <div v-else class="user-rankings">
              <div
                v-for="(user, index) in userRankings"
                :key="user.user_id"
                class="ranking-item"
              >
                <div class="ranking-position">
                  <div class="position-number" :class="{ 
                    gold: index === 0, 
                    silver: index === 1, 
                    bronze: index === 2 
                  }">
                    {{ index + 1 }}
                  </div>
                </div>
                <div class="user-info">
                  <div class="user-name">{{ user.display_name }}</div>
                  <div class="user-stats">
                    <span>{{ user.job_count }} 個任務</span>
                    <span>${{ user.total_cost.toFixed(4) }}</span>
                  </div>
                </div>
                <div class="ranking-progress">
                  <el-progress
                    :percentage="Math.round((user.job_count / userRankings[0]?.job_count) * 100)"
                    :stroke-width="6"
                    :show-text="false"
                    :color="index < 3 ? '#409eff' : '#e6e6e6'"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 系統狀態 -->
        <div class="content-card">
          <div class="card-header">
            <h3 class="card-title">系統狀態</h3>
            <div class="card-actions">
              <el-button 
                type="text" 
                size="small" 
                @click="cleanupOldFiles"
                :loading="cleanupLoading"
              >
                <el-icon><Delete /></el-icon>
                清理檔案
              </el-button>
            </div>
          </div>
          <div class="card-body">
            <div class="system-health">
              <div class="health-item">
                <div class="health-label">系統狀態</div>
                <div class="health-value">
                  <el-tag 
                    :type="isSystemHealthy ? 'success' : 'danger'"
                    size="small"
                  >
                    {{ isSystemHealthy ? '正常' : '異常' }}
                  </el-tag>
                </div>
              </div>
              
              <div class="health-item" v-if="systemMetrics">
                <div class="health-label">排隊任務</div>
                <div class="health-value">
                  {{ systemMetrics.jobs?.pending || 0 }} 個
                </div>
              </div>
              
              <div class="health-item" v-if="systemMetrics">
                <div class="health-label">處理中任務</div>
                <div class="health-value">
                  {{ systemMetrics.jobs?.processing || 0 }} 個
                </div>
              </div>
              
              <div class="health-item">
                <div class="health-label">上次更新</div>
                <div class="health-value">
                  {{ formatTime(new Date().toISOString()) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最新任務 -->
    <div class="recent-jobs-section">
      <div class="content-card">
        <div class="card-header">
          <h3 class="card-title">最新任務</h3>
          <div class="card-actions">
            <el-button type="text" @click="$router.push('/admin/jobs')">
              查看全部任務
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="card-body">
          <div v-if="loading" class="loading-state">
            <el-skeleton :rows="3" animated />
          </div>
          <div v-else-if="recentJobs.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Document /></el-icon>
            <div class="empty-title">暫無任務記錄</div>
          </div>
          <div v-else class="jobs-table">
            <el-table :data="recentJobs" style="width: 100%">
              <el-table-column prop="original_filename" label="檔案名稱" min-width="200">
                <template #default="{ row }">
                  <div class="file-info">
                    <div class="file-icon" :class="getFileExtension(row.original_filename)">
                      {{ getFileExtension(row.original_filename).toUpperCase() }}
                    </div>
                    <span class="file-name">{{ row.original_filename }}</span>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column prop="user_name" label="用戶" width="120" />
              
              <el-table-column prop="target_languages" label="目標語言" width="150">
                <template #default="{ row }">
                  <div class="language-tags">
                    <el-tag 
                      v-for="lang in row.target_languages" 
                      :key="lang"
                      size="small"
                      type="primary"
                    >
                      {{ getLanguageText(lang) }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column prop="status" label="狀態" width="100">
                <template #default="{ row }">
                  <el-tag 
                    :type="getStatusTagType(row.status)"
                    size="small"
                  >
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="created_at" label="建立時間" width="120">
                <template #default="{ row }">
                  {{ formatTime(row.created_at) }}
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="80">
                <template #default="{ row }">
                  <el-button 
                    type="text" 
                    size="small"
                    @click="viewJobDetail(row.job_uuid)"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAdminStore } from '@/stores/admin'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  Download, ArrowDown, Refresh, DataBoard, SuccessFilled,
  User, Money, Delete, ArrowRight, Document
} from '@element-plus/icons-vue'

// Router 和 Store
const router = useRouter()
const adminStore = useAdminStore()

// 圖表引用
const dailyChartRef = ref()
const costChartRef = ref()

// 響應式數據
const loading = ref(false)
const cleanupLoading = ref(false)
const chartPeriod = ref('month')
const dailyChart = ref(null)
const costChart = ref(null)

// 計算屬性
const overviewStats = computed(() => adminStore.overviewStats)
const dailyStats = computed(() => adminStore.dailyStats)
const userRankings = computed(() => adminStore.userRankings.slice(0, 10))
const isSystemHealthy = computed(() => adminStore.isSystemHealthy)
const systemMetrics = computed(() => adminStore.systemMetrics)

const recentJobs = computed(() => {
  return adminStore.allJobs.slice(0, 10)
})

// 語言映射
const languageMap = {
  'zh-TW': '繁中',
  'zh-CN': '簡中',
  'en': '英文',
  'ja': '日文',
  'ko': '韓文',
  'vi': '越文'
}

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      adminStore.fetchStats(chartPeriod.value),
      adminStore.fetchAllJobs({ per_page: 10 }),
      adminStore.fetchSystemHealth(),
      adminStore.fetchSystemMetrics()
    ])
    
    await nextTick()
    initCharts()
  } catch (error) {
    console.error('刷新資料失敗:', error)
    ElMessage.error('刷新資料失敗')
  } finally {
    loading.value = false
  }
}

const handlePeriodChange = async () => {
  await refreshData()
}

const handleExportCommand = async (command) => {
  try {
    await adminStore.exportReport(command)
  } catch (error) {
    console.error('匯出報表失敗:', error)
    ElMessage.error('匯出報表失敗')
  }
}

const cleanupOldFiles = async () => {
  try {
    cleanupLoading.value = true
    await adminStore.cleanupOldFiles()
    ElMessage.success('檔案清理完成')
  } catch (error) {
    console.error('檔案清理失敗:', error)
  } finally {
    cleanupLoading.value = false
  }
}

const viewJobDetail = (jobUuid) => {
  router.push(`/job/${jobUuid}`)
}

const initCharts = () => {
  initDailyChart()
  initCostChart()
}

const initDailyChart = () => {
  if (!dailyChartRef.value || dailyStats.value.length === 0) return
  
  if (dailyChart.value) {
    dailyChart.value.dispose()
  }
  
  dailyChart.value = echarts.init(dailyChartRef.value)
  
  const dates = dailyStats.value.map(stat => stat.date)
  const jobs = dailyStats.value.map(stat => stat.jobs)
  const completed = dailyStats.value.map(stat => stat.completed)
  const failed = dailyStats.value.map(stat => stat.failed)
  
  const option = {
    title: {
      text: '每日任務統計',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['總任務', '已完成', '失敗']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value)
          return `${date.getMonth() + 1}/${date.getDate()}`
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '總任務',
        type: 'bar',
        data: jobs,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '已完成',
        type: 'bar',
        data: completed,
        itemStyle: { color: '#67c23a' }
      },
      {
        name: '失敗',
        type: 'bar',
        data: failed,
        itemStyle: { color: '#f56c6c' }
      }
    ]
  }
  
  dailyChart.value.setOption(option)
}

const initCostChart = () => {
  if (!costChartRef.value || dailyStats.value.length === 0) return
  
  if (costChart.value) {
    costChart.value.dispose()
  }
  
  costChart.value = echarts.init(costChartRef.value)
  
  const dates = dailyStats.value.map(stat => stat.date)
  const costs = dailyStats.value.map(stat => stat.cost)
  
  const option = {
    title: {
      text: '每日成本趨勢',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0]
        return `${data.name}<br/>成本: $${data.value.toFixed(4)}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value)
          return `${date.getMonth() + 1}/${date.getDate()}`
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => `$${value.toFixed(4)}`
      }
    },
    series: [
      {
        name: '成本',
        type: 'line',
        data: costs,
        smooth: true,
        itemStyle: { color: '#e6a23c' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
            { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
          ])
        }
      }
    ]
  }
  
  costChart.value.setOption(option)
}

const getFileExtension = (filename) => {
  return filename.split('.').pop().toLowerCase()
}

const getLanguageText = (langCode) => {
  return languageMap[langCode] || langCode
}

const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '等待',
    'PROCESSING': '處理中',
    'COMPLETED': '完成',
    'FAILED': '失敗',
    'RETRY': '重試'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    'PENDING': 'info',
    'PROCESSING': 'primary',
    'COMPLETED': 'success',
    'FAILED': 'danger',
    'RETRY': 'warning'
  }
  return typeMap[status] || 'info'
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const time = new Date(timestamp)
  const diff = now - time
  
  if (diff < 60000) return '剛剛'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}時前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return time.toLocaleDateString('zh-TW')
}

// 視窗大小調整處理
const handleResize = () => {
  if (dailyChart.value) {
    dailyChart.value.resize()
  }
  if (costChart.value) {
    costChart.value.resize()
  }
}

// 生命週期
onMounted(async () => {
  await refreshData()
  
  // 監聽視窗大小變化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  if (dailyChart.value) {
    dailyChart.value.dispose()
  }
  if (costChart.value) {
    costChart.value.dispose()
  }
})
</script>

<style lang="scss" scoped>
.admin-view {
  .overview-section {
    margin-bottom: 24px;
    
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
      gap: 16px;
      
      .stat-total {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-top: 4px;
      }
    }
  }
  
  .charts-section {
    margin-bottom: 24px;
    
    .chart-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
      
      @media (max-width: 1200px) {
        grid-template-columns: 1fr;
      }
      
      .chart-card {
        .chart-container {
          height: 300px;
          width: 100%;
        }
      }
    }
  }
  
  .info-section {
    margin-bottom: 24px;
    
    .info-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 16px;
      
      @media (max-width: 768px) {
        grid-template-columns: 1fr;
      }
    }
    
    .user-rankings {
      .ranking-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);
        
        &:last-child {
          border-bottom: none;
        }
        
        .ranking-position {
          margin-right: 16px;
          
          .position-number {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            background-color: var(--el-color-info);
            
            &.gold {
              background: linear-gradient(45deg, #ffd700, #ffed4e);
              color: #8b4513;
            }
            
            &.silver {
              background: linear-gradient(45deg, #c0c0c0, #e8e8e8);
              color: #666;
            }
            
            &.bronze {
              background: linear-gradient(45deg, #cd7f32, #daa520);
              color: white;
            }
          }
        }
        
        .user-info {
          flex: 1;
          min-width: 0;
          
          .user-name {
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }
          
          .user-stats {
            display: flex;
            gap: 16px;
            font-size: 13px;
            color: var(--el-text-color-secondary);
          }
        }
        
        .ranking-progress {
          width: 80px;
          margin-left: 16px;
        }
      }
    }
    
    .system-health {
      .health-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);
        
        &:last-child {
          border-bottom: none;
        }
        
        .health-label {
          color: var(--el-text-color-regular);
        }
        
        .health-value {
          font-weight: 500;
          color: var(--el-text-color-primary);
        }
      }
    }
  }
  
  .recent-jobs-section {
    .file-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .file-icon {
        width: 24px;
        height: 24px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 8px;
        font-weight: bold;
        color: white;
        flex-shrink: 0;
        
        &.docx, &.doc { background-color: #2b579a; }
        &.pptx, &.ppt { background-color: #d24726; }
        &.xlsx, &.xls { background-color: #207245; }
        &.pdf { background-color: #ff0000; }
      }
      
      .file-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    
    .language-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
  }
}

.loading-state {
  padding: 20px 0;
}
</style>