<template>
  <div class="job-list-view">
    <!-- 頁面標題 -->
    <div class="page-header">
      <h1 class="page-title">任務列表</h1>
      <div class="page-actions">
        <el-button type="primary" @click="$router.push('/upload')">
          <el-icon><Upload /></el-icon>
          上傳檔案
        </el-button>
      </div>
    </div>

    <!-- 篩選和搜尋 -->
    <div class="content-card">
      <div class="filters-section">
        <div class="filters-row">
          <div class="filter-group">
            <label>狀態篩選:</label>
            <el-select 
              v-model="filters.status" 
              @change="handleFilterChange"
              style="width: 120px"
            >
              <el-option label="全部" value="all" />
              <el-option label="等待中" value="PENDING" />
              <el-option label="處理中" value="PROCESSING" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="失敗" value="FAILED" />
              <el-option label="重試中" value="RETRY" />
            </el-select>
          </div>
          
          <div class="filter-group">
            <label>檔案搜尋:</label>
            <el-input
              v-model="filters.search"
              placeholder="請輸入檔案名稱"
              style="width: 200px"
              clearable
              @input="handleSearchChange"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="filter-actions">
            <el-button @click="refreshJobs" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="clearFilters">
              <el-icon><Close /></el-icon>
              清除篩選
            </el-button>
          </div>
        </div>
        
        <!-- 統計資訊 -->
        <div class="stats-row">
          <div class="stat-item">
            <span class="stat-label">總計:</span>
            <span class="stat-value">{{ jobStats.total }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">等待:</span>
            <span class="stat-value stat-pending">{{ jobStats.pending }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">處理:</span>
            <span class="stat-value stat-processing">{{ jobStats.processing }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">完成:</span>
            <span class="stat-value stat-completed">{{ jobStats.completed }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">失敗:</span>
            <span class="stat-value stat-failed">{{ jobStats.failed }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 任務列表 -->
    <div class="content-card">
      <div class="card-body">
        <!-- 載入狀態 -->
        <div v-if="loading && jobs.length === 0" class="loading-state">
          <el-skeleton :rows="5" animated />
        </div>
        
        <!-- 空狀態 -->
        <div v-else-if="filteredJobs.length === 0" class="empty-state">
          <el-icon class="empty-icon">
            <Document v-if="jobs.length === 0" />
            <Search v-else />
          </el-icon>
          <div class="empty-title">
            {{ jobs.length === 0 ? '暫無任務記錄' : '未找到符合條件的任務' }}
          </div>
          <div class="empty-description">
            {{ jobs.length === 0 
              ? '開始上傳您的第一個檔案進行翻譯吧！' 
              : '請嘗試調整篩選條件或搜尋關鍵字' }}
          </div>
          <el-button v-if="jobs.length === 0" type="primary" @click="$router.push('/upload')">
            立即上傳
          </el-button>
        </div>
        
        <!-- 任務列表 -->
        <div v-else class="jobs-grid">
          <div
            v-for="job in filteredJobs"
            :key="job.job_uuid"
            class="job-card"
            @click="viewJobDetail(job.job_uuid)"
          >
            <!-- 任務標題 -->
            <div class="job-header">
              <div class="job-title-section">
                <div class="file-icon" :class="getFileExtension(job.original_filename)">
                  {{ getFileExtension(job.original_filename).toUpperCase() }}
                </div>
                <div class="job-title-info">
                  <div class="job-title" :title="job.original_filename">
                    {{ job.original_filename }}
                  </div>
                  <div class="job-meta">
                    <span class="file-size">{{ formatFileSize(job.file_size) }}</span>
                    <span class="upload-time">{{ formatTime(job.created_at) }}</span>
                  </div>
                </div>
              </div>
              
              <div class="job-actions" @click.stop>
                <el-dropdown 
                  trigger="click" 
                  @command="handleJobAction($event, job)"
                  placement="bottom-end"
                >
                  <el-button type="text" size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view">
                        <el-icon><View /></el-icon>
                        查看詳情
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="job.status === 'COMPLETED'" 
                        command="download"
                      >
                        <el-icon><Download /></el-icon>
                        下載檔案
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="job.status === 'FAILED'" 
                        command="retry"
                      >
                        <el-icon><RefreshRight /></el-icon>
                        重新翻譯
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="['PENDING', 'PROCESSING'].includes(job.status)" 
                        command="cancel"
                      >
                        <el-icon><CircleClose /></el-icon>
                        取消任務
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <el-icon><Delete /></el-icon>
                        刪除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
            
            <!-- 翻譯語言 -->
            <div class="job-languages">
              <div class="language-info">
                <span class="language-label">來源:</span>
                <span class="language-tag source">
                  {{ getLanguageText(job.source_language) }}
                </span>
              </div>
              <div class="language-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
              <div class="language-info">
                <span class="language-label">目標:</span>
                <div class="language-tags">
                  <span 
                    v-for="lang in job.target_languages" 
                    :key="lang"
                    class="language-tag target"
                  >
                    {{ getLanguageText(lang) }}
                  </span>
                </div>
              </div>
            </div>
            
            <!-- 任務狀態 -->
            <div class="job-status-section">
              <div class="status-info">
                <div class="status-badge" :class="job.status.toLowerCase()">
                  <el-icon>
                    <component :is="getStatusIcon(job.status)" />
                  </el-icon>
                  <span>{{ getStatusText(job.status) }}</span>
                </div>
                <div v-if="job.retry_count > 0" class="retry-count">
                  重試 {{ job.retry_count }} 次
                </div>
              </div>
              
              <!-- 進度條 -->
              <div v-if="job.status === 'PROCESSING' && job.progress > 0" class="job-progress">
                <div class="progress-info">
                  <span>翻譯進度</span>
                  <span>{{ Math.round(job.progress) }}%</span>
                </div>
                <el-progress
                  :percentage="job.progress"
                  :stroke-width="6"
                  :show-text="false"
                  status="success"
                />
              </div>
              
              <!-- 錯誤訊息 -->
              <div v-if="job.status === 'FAILED' && job.error_message" class="error-message">
                <el-icon><WarningFilled /></el-icon>
                <span>{{ job.error_message }}</span>
              </div>
            </div>
            
            <!-- 任務資訊 -->
            <div class="job-footer">
              <div class="job-info-grid">
                <div class="info-item" v-if="job.processing_started_at">
                  <span class="info-label">開始:</span>
                  <span class="info-value">{{ formatTime(job.processing_started_at) }}</span>
                </div>
                <div class="info-item" v-if="job.completed_at">
                  <span class="info-label">完成:</span>
                  <span class="info-value">{{ formatTime(job.completed_at) }}</span>
                </div>
                <div class="info-item" v-if="job.total_cost > 0">
                  <span class="info-label">成本:</span>
                  <span class="info-value">${{ job.total_cost.toFixed(4) }}</span>
                </div>
                <div class="info-item" v-if="job.total_tokens > 0">
                  <span class="info-label">Token:</span>
                  <span class="info-value">{{ job.total_tokens.toLocaleString() }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分頁 -->
        <div class="pagination-section" v-if="pagination.pages > 1">
          <el-pagination
            v-model:current-page="pagination.page"
            :page-size="pagination.per_page"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useJobsStore } from '@/stores/jobs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce } from 'lodash-es'
import {
  Upload, Search, Refresh, Close, Document, More, View, Download,
  RefreshRight, CircleClose, Delete, ArrowRight, Clock, Loading,
  SuccessFilled, CircleCloseFilled, WarningFilled, InfoFilled
} from '@element-plus/icons-vue'
import { initWebSocket } from '@/utils/websocket'

// Router 和 Store
const router = useRouter()
const jobsStore = useJobsStore()

// Debug: 檢查 store 方法
console.log('[DEBUG] JobsStore methods:', Object.getOwnPropertyNames(jobsStore))
console.log('[DEBUG] subscribeToJobUpdates exists:', typeof jobsStore.subscribeToJobUpdates)
console.log('[DEBUG] subscribeToJobUpdates is function:', typeof jobsStore.subscribeToJobUpdates === 'function')

// 響應式數據
const loading = ref(false)
const filters = ref({
  status: 'all',
  search: ''
})

// 計算屬性
const jobs = computed(() => jobsStore.jobs)
const pagination = computed(() => jobsStore.pagination)
const jobStats = computed(() => jobsStore.jobStats)

const filteredJobs = computed(() => {
  let filtered = jobs.value

  // 狀態篩選
  if (filters.value.status !== 'all') {
    filtered = filtered.filter(job => job.status === filters.value.status)
  }

  // 搜尋篩選
  if (filters.value.search.trim()) {
    const searchTerm = filters.value.search.toLowerCase().trim()
    filtered = filtered.filter(job =>
      job.original_filename.toLowerCase().includes(searchTerm)
    )
  }

  return filtered
})

// 語言映射
const languageMap = {
  'auto': '自動偵測',
  'zh-TW': '繁中',
  'zh-CN': '簡中',
  'en': '英文',
  'ja': '日文',
  'ko': '韓文',
  'vi': '越文',
  'th': '泰文',
  'id': '印尼文',
  'ms': '馬來文'
}

// 方法
const refreshJobs = async () => {
  loading.value = true
  try {
    await jobsStore.fetchJobs({
      page: pagination.value.page,
      per_page: pagination.value.per_page,
      status: filters.value.status === 'all' ? undefined : filters.value.status
    })
  } catch (error) {
    console.error('刷新任務列表失敗:', error)
  } finally {
    loading.value = false
  }
}

const clearFilters = () => {
  filters.value.status = 'all'
  filters.value.search = ''
  handleFilterChange()
}

const handleFilterChange = debounce(() => {
  refreshJobs()
}, 300)

const handleSearchChange = debounce(() => {
  // 搜尋是前端過濾，不需要重新請求 API
}, 300)

const handlePageChange = (page) => {
  jobsStore.pagination.page = page
  refreshJobs()
}

const handleSizeChange = (size) => {
  jobsStore.pagination.per_page = size
  jobsStore.pagination.page = 1
  refreshJobs()
}

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

const handleJobAction = async (action, job) => {
  switch (action) {
    case 'view':
      viewJobDetail(job.job_uuid)
      break
      
    case 'download':
      try {
        if (job.target_languages.length === 1) {
          // 單一語言直接下載
          const ext = getFileExtension(job.original_filename)
          const filename = `${job.original_filename.replace(/\.[^/.]+$/, '')}_${job.target_languages[0]}_translated.${ext}`
          await jobsStore.downloadFile(job.job_uuid, job.target_languages[0], filename)
        } else {
          // 多語言打包下載
          const filename = `${job.original_filename.replace(/\.[^/.]+$/, '')}_translated.zip`
          await jobsStore.downloadAllFiles(job.job_uuid, filename)
        }
      } catch (error) {
        console.error('下載失敗:', error)
      }
      break
      
    case 'retry':
      try {
        await ElMessageBox.confirm('確定要重新翻譯此檔案嗎？', '確認重試', {
          confirmButtonText: '確定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await jobsStore.retryJob(job.job_uuid)
      } catch (error) {
        if (error !== 'cancel') {
          console.error('重試任務失敗:', error)
        }
      }
      break
      
    case 'cancel':
      try {
        await ElMessageBox.confirm('確定要取消此任務嗎？', '確認取消', {
          confirmButtonText: '確定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await jobsStore.cancelJob(job.job_uuid)
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消任務失敗:', error)
        }
      }
      break
      
    case 'delete':
      try {
        await ElMessageBox.confirm('確定要刪除此任務嗎？此操作無法撤銷。', '確認刪除', {
          confirmButtonText: '確定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          message: `<strong>檔案:</strong> ${job.original_filename}<br/><strong>注意:</strong> 刪除後無法恢復`
        })
        
        await jobsStore.deleteJob(job.job_uuid)
      } catch (error) {
        if (error !== 'cancel') {
          console.error('刪除任務失敗:', error)
        }
      }
      break
  }
}

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

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

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', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

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

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

const getStatusIcon = (status) => {
  const iconMap = {
    'PENDING': 'Clock',
    'PROCESSING': 'Loading',
    'COMPLETED': 'SuccessFilled',
    'FAILED': 'CircleCloseFilled',
    'RETRY': 'RefreshRight'
  }
  return iconMap[status] || 'InfoFilled'
}

// 生命週期
onMounted(async () => {
  // 暫時禁用 WebSocket 避免連接錯誤
  // initWebSocket()
  
  // 載入任務列表
  await refreshJobs()
  
  // 為所有處理中的任務訂閱狀態更新
  const processingJobs = jobs.value.filter(job => 
    ['PENDING', 'PROCESSING', 'RETRY'].includes(job.status)
  )
  
  processingJobs.forEach(job => {
    console.log(`[DEBUG] Attempting to subscribe to job: ${job.job_uuid}`)
    if (typeof jobsStore.subscribeToJobUpdates === 'function') {
      jobsStore.subscribeToJobUpdates(job.job_uuid)
    } else {
      console.error('[ERROR] subscribeToJobUpdates is not a function:', typeof jobsStore.subscribeToJobUpdates)
    }
  })
})

// 監聽任務列表變化，自動訂閱新的處理中任務
watch(jobs, (newJobs, oldJobs) => {
  const oldUuids = oldJobs?.map(job => job.job_uuid) || []
  const newProcessingJobs = newJobs.filter(job => 
    ['PENDING', 'PROCESSING', 'RETRY'].includes(job.status) &&
    !oldUuids.includes(job.job_uuid)
  )
  
  newProcessingJobs.forEach(job => {
    console.log(`[DEBUG] Attempting to subscribe to new job: ${job.job_uuid}`)
    if (typeof jobsStore.subscribeToJobUpdates === 'function') {
      jobsStore.subscribeToJobUpdates(job.job_uuid)
    } else {
      console.error('[ERROR] subscribeToJobUpdates is not a function in watch:', typeof jobsStore.subscribeToJobUpdates)
    }
  })
}, { deep: true })

// 組件卸載時清理輪詢
onUnmounted(() => {
  console.log('[DEBUG] 組件卸載，停止所有輪詢')
  jobsStore.stopAllPolling()
})
</script>

<style lang="scss" scoped>
.job-list-view {
  .filters-section {
    .filters-row {
      display: flex;
      align-items: center;
      gap: 24px;
      margin-bottom: 16px;
      flex-wrap: wrap;
      
      .filter-group {
        display: flex;
        align-items: center;
        gap: 8px;
        
        label {
          font-size: 14px;
          color: var(--el-text-color-regular);
          white-space: nowrap;
        }
      }
      
      .filter-actions {
        margin-left: auto;
        display: flex;
        gap: 8px;
        
        @media (max-width: 768px) {
          margin-left: 0;
          width: 100%;
        }
      }
    }
    
    .stats-row {
      display: flex;
      gap: 24px;
      padding: 12px 16px;
      background-color: var(--el-fill-color-lighter);
      border-radius: 6px;
      flex-wrap: wrap;
      
      .stat-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 13px;
        
        .stat-label {
          color: var(--el-text-color-regular);
        }
        
        .stat-value {
          font-weight: 600;
          color: var(--el-text-color-primary);
          
          &.stat-pending { color: var(--el-color-info); }
          &.stat-processing { color: var(--el-color-primary); }
          &.stat-completed { color: var(--el-color-success); }
          &.stat-failed { color: var(--el-color-danger); }
        }
      }
    }
  }
  
  .jobs-grid {
    display: grid;
    gap: 16px;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    
    @media (max-width: 480px) {
      grid-template-columns: 1fr;
    }
    
    .job-card {
      border: 1px solid var(--el-border-color-lighter);
      border-radius: 8px;
      padding: 16px;
      background: var(--el-bg-color);
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: var(--el-color-primary);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        transform: translateY(-1px);
      }
      
      .job-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
        
        .job-title-section {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          flex: 1;
          min-width: 0;
          
          .file-icon {
            width: 36px;
            height: 36px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            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; }
          }
          
          .job-title-info {
            flex: 1;
            min-width: 0;
            
            .job-title {
              font-weight: 600;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .job-meta {
              display: flex;
              gap: 12px;
              font-size: 12px;
              color: var(--el-text-color-secondary);
            }
          }
        }
      }
      
      .job-languages {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        font-size: 13px;
        
        .language-info {
          display: flex;
          align-items: center;
          gap: 4px;
          
          .language-label {
            color: var(--el-text-color-secondary);
            font-size: 12px;
          }
        }
        
        .language-arrow {
          color: var(--el-text-color-placeholder);
          font-size: 12px;
        }
        
        .language-tag {
          display: inline-block;
          padding: 2px 6px;
          border-radius: 3px;
          font-size: 11px;
          font-weight: 500;
          
          &.source {
            background-color: var(--el-color-info-light-8);
            color: var(--el-color-info);
            border: 1px solid var(--el-color-info-light-5);
          }
          
          &.target {
            background-color: var(--el-color-primary-light-8);
            color: var(--el-color-primary);
            border: 1px solid var(--el-color-primary-light-5);
            margin-right: 4px;
            
            &:last-child {
              margin-right: 0;
            }
          }
        }
        
        .language-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 2px;
        }
      }
      
      .job-status-section {
        margin-bottom: 12px;
        
        .status-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          
          .status-badge {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
            
            &.pending {
              background-color: var(--el-color-info-light-9);
              color: var(--el-color-info);
              border: 1px solid var(--el-color-info-light-5);
            }
            
            &.processing {
              background-color: var(--el-color-primary-light-9);
              color: var(--el-color-primary);
              border: 1px solid var(--el-color-primary-light-5);
            }
            
            &.completed {
              background-color: var(--el-color-success-light-9);
              color: var(--el-color-success);
              border: 1px solid var(--el-color-success-light-5);
            }
            
            &.failed {
              background-color: var(--el-color-danger-light-9);
              color: var(--el-color-danger);
              border: 1px solid var(--el-color-danger-light-5);
            }
            
            &.retry {
              background-color: var(--el-color-warning-light-9);
              color: var(--el-color-warning);
              border: 1px solid var(--el-color-warning-light-5);
            }
          }
          
          .retry-count {
            font-size: 11px;
            color: var(--el-text-color-secondary);
          }
        }
        
        .job-progress {
          .progress-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;
            font-size: 12px;
            color: var(--el-text-color-regular);
          }
        }
        
        .error-message {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 6px 8px;
          background-color: var(--el-color-danger-light-9);
          border: 1px solid var(--el-color-danger-light-5);
          border-radius: 4px;
          color: var(--el-color-danger);
          font-size: 12px;
          margin-top: 6px;
        }
      }
      
      .job-footer {
        .job-info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 8px;
          font-size: 12px;
          
          .info-item {
            display: flex;
            justify-content: space-between;
            
            .info-label {
              color: var(--el-text-color-secondary);
            }
            
            .info-value {
              color: var(--el-text-color-primary);
              font-weight: 500;
            }
          }
        }
      }
    }
  }
  
  .pagination-section {
    margin-top: 24px;
    display: flex;
    justify-content: center;
  }
}

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