<template>
  <div class="home-view">
    <!-- 歡迎區域 -->
    <div class="welcome-section">
      <div class="welcome-card content-card">
        <div class="welcome-content">
          <div class="welcome-text">
            <h1 class="welcome-title">
              歡迎使用 PANJIT 文件翻譯系統
              <el-tag v-if="authStore.isAdmin" type="warning" size="small">管理員</el-tag>
            </h1>
            <p class="welcome-subtitle">
              歡迎回來，{{ authStore.userName }}！
              今天是個適合處理翻譯任務的好日子。
            </p>
          </div>
          <div class="welcome-actions">
            <el-button type="primary" size="large" @click="$router.push('/upload')">
              <el-icon><Upload /></el-icon>
              開始上傳檔案
            </el-button>
            <el-button size="large" @click="$router.push('/jobs')">
              <el-icon><List /></el-icon>
              查看我的任務
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 統計概覽 -->
    <div class="stats-section">
      <div class="section-title">
        <h2>任務統計</h2>
        <el-button type="text" @click="refreshStats">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
      
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon primary">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-value">{{ jobStats.total }}</div>
          <div class="stat-label">總任務數</div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon warning">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-value">{{ jobStats.pending + jobStats.processing }}</div>
          <div class="stat-label">處理中</div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon success">
            <el-icon><SuccessFilled /></el-icon>
          </div>
          <div class="stat-value">{{ jobStats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon danger">
            <el-icon><CircleCloseFilled /></el-icon>
          </div>
          <div class="stat-value">{{ jobStats.failed }}</div>
          <div class="stat-label">失敗</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('/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 class="empty-description">
              開始上傳您的第一個檔案進行翻譯吧！
            </div>
            <el-button type="primary" @click="$router.push('/upload')">
              立即上傳
            </el-button>
          </div>
          
          <div v-else class="job-list">
            <div
              v-for="job in recentJobs"
              :key="job.job_uuid"
              class="job-item"
              @click="viewJobDetail(job.job_uuid)"
            >
              <div class="job-icon">
                <div class="file-icon" :class="getFileExtension(job.original_filename)">
                  {{ getFileExtension(job.original_filename).toUpperCase() }}
                </div>
              </div>
              
              <div class="job-info">
                <div class="job-name">{{ job.original_filename }}</div>
                <div class="job-details">
                  <span class="job-size">{{ formatFileSize(job.file_size) }}</span>
                  <span class="job-languages">
                    {{ job.target_languages.join(', ') }}
                  </span>
                </div>
              </div>
              
              <div class="job-status">
                <div class="status-badge" :class="job.status.toLowerCase()">
                  {{ getStatusText(job.status) }}
                </div>
                <div v-if="job.progress > 0 && job.status === 'PROCESSING'" class="job-progress">
                  <el-progress
                    :percentage="job.progress"
                    :stroke-width="4"
                    :show-text="false"
                    color="#409eff"
                  />
                </div>
              </div>
              
              <div class="job-time">
                {{ formatTime(job.created_at) }}
              </div>
              
              <div class="job-actions" @click.stop>
                <el-dropdown trigger="click" @command="handleJobAction($event, job)">
                  <el-button type="text" size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view">查看詳情</el-dropdown-item>
                      <el-dropdown-item 
                        v-if="job.status === 'COMPLETED'" 
                        command="download"
                      >
                        下載檔案
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="job.status === 'FAILED'" 
                        command="retry"
                      >
                        重新翻譯
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>刪除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 系統公告 -->
    <div class="announcements-section" v-if="announcements.length > 0">
      <div class="content-card">
        <div class="card-header">
          <h3 class="card-title">系統公告</h3>
        </div>
        <div class="card-body">
          <div class="announcements-list">
            <div
              v-for="announcement in announcements"
              :key="announcement.id"
              class="announcement-item"
              :class="announcement.type"
            >
              <div class="announcement-icon">
                <el-icon>
                  <component :is="getAnnouncementIcon(announcement.type)" />
                </el-icon>
              </div>
              <div class="announcement-content">
                <div class="announcement-title">{{ announcement.title }}</div>
                <div class="announcement-message">{{ announcement.message }}</div>
                <div class="announcement-time">{{ formatTime(announcement.created_at) }}</div>
              </div>
              <div class="announcement-actions" v-if="announcement.actionText">
                <el-button type="text" size="small" @click="handleAnnouncementAction(announcement)">
                  {{ announcement.actionText }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useJobsStore } from '@/stores/jobs'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Upload, List, Refresh, Files, Clock, SuccessFilled, CircleCloseFilled,
  ArrowRight, Document, More, InfoFilled, WarningFilled, CircleCheckFilled
} from '@element-plus/icons-vue'

// Router 和 Stores
const router = useRouter()
const authStore = useAuthStore()
const jobsStore = useJobsStore()

// 響應式數據
const loading = ref(false)
const announcements = ref([
  {
    id: 1,
    type: 'info',
    title: '系統更新通知',
    message: '系統已更新至最新版本，新增了批量下載功能。',
    created_at: new Date().toISOString(),
    actionText: '了解更多'
  },
  {
    id: 2,
    type: 'warning',
    title: '維護通知',
    message: '系統將於本週日凌晨 2:00-4:00 進行定期維護。',
    created_at: new Date(Date.now() - 86400000).toISOString()
  }
])

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

const recentJobs = computed(() => {
  return jobsStore.jobs.slice(0, 5)
})

// 方法
const refreshStats = async () => {
  try {
    await jobsStore.fetchJobs({ per_page: 10 })
    ElMessage.success('統計資料已刷新')
  } catch (error) {
    console.error('刷新統計失敗:', error)
  }
}

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

const handleJobAction = async (action, job) => {
  switch (action) {
    case 'view':
      viewJobDetail(job.job_uuid)
      break
      
    case 'download':
      // 如果只有一個目標語言，直接下載
      if (job.target_languages.length === 1) {
        const filename = `${job.original_filename.replace(/\.[^/.]+$/, '')}_${job.target_languages[0]}_translated.${getFileExtension(job.original_filename)}`
        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)
      }
      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 'delete':
      try {
        await ElMessageBox.confirm('確定要刪除此任務嗎？此操作無法撤銷。', '確認刪除', {
          confirmButtonText: '確定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await jobsStore.deleteJob(job.job_uuid)
      } catch (error) {
        if (error !== 'cancel') {
          console.error('刪除任務失敗:', error)
        }
      }
      break
  }
}

const handleAnnouncementAction = (announcement) => {
  if (announcement.actionUrl) {
    window.open(announcement.actionUrl, '_blank')
  } else {
    ElMessage.info('功能開發中，敬請期待')
  }
}

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

const formatTime = (timestamp) => {
  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 getAnnouncementIcon = (type) => {
  const iconMap = {
    info: 'InfoFilled',
    warning: 'WarningFilled',
    success: 'CircleCheckFilled',
    error: 'CircleCloseFilled'
  }
  return iconMap[type] || 'InfoFilled'
}

// 生命週期
onMounted(async () => {
  loading.value = true
  console.log('🏠 [HomeView] onMounted 開始執行')
  console.log('🏠 [HomeView] 當前認證狀態', {
    isAuthenticated: authStore.isAuthenticated,
    user: authStore.user,
    token: authStore.token
  })
  
  try {
    // 延遲載入任務列表，避免登入後立即請求造成認證問題
    console.log('🏠 [HomeView] 等待 500ms 後載入任務列表')
    await new Promise(resolve => setTimeout(resolve, 500))
    
    console.log('🏠 [HomeView] 開始載入任務列表')
    // 載入最近的任務
    await jobsStore.fetchJobs({ per_page: 10 })
    console.log('🏠 [HomeView] 任務列表載入成功')
  } catch (error) {
    console.error('❌ [HomeView] 載入任務失敗:', error)
    // 如果是認證錯誤，不要顯示錯誤訊息，因為 request.js 會處理
    if (!error.message?.includes('認證') && !error.response?.status === 401) {
      ElMessage.error('載入任務失敗，請稍後重試')
    }
  } finally {
    loading.value = false
    console.log('🏠 [HomeView] onMounted 執行完畢')
  }
})
</script>

<style lang="scss" scoped>
.home-view {
  .welcome-section {
    margin-bottom: 32px;
    
    .welcome-card {
      background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
      color: white;
      border: none;
      
      .welcome-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        @media (max-width: 768px) {
          flex-direction: column;
          text-align: center;
          gap: 24px;
        }
        
        .welcome-text {
          .welcome-title {
            font-size: 28px;
            font-weight: bold;
            margin: 0 0 12px 0;
            display: flex;
            align-items: center;
            gap: 12px;
            
            @media (max-width: 768px) {
              font-size: 24px;
              justify-content: center;
              flex-wrap: wrap;
            }
          }
          
          .welcome-subtitle {
            font-size: 16px;
            opacity: 0.9;
            margin: 0;
            line-height: 1.5;
          }
        }
        
        .welcome-actions {
          display: flex;
          gap: 12px;
          
          @media (max-width: 480px) {
            flex-direction: column;
            width: 100%;
          }
        }
      }
    }
  }
  
  .stats-section {
    margin-bottom: 32px;
    
    .section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h2 {
        margin: 0;
        color: var(--el-text-color-primary);
        font-size: 20px;
        font-weight: 600;
      }
    }
    
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      
      @media (max-width: 480px) {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
      }
    }
  }
  
  .recent-jobs-section {
    margin-bottom: 32px;
    
    .job-list {
      .job-item {
        display: flex;
        align-items: center;
        padding: 16px;
        border: 1px solid var(--el-border-color-lighter);
        border-radius: 8px;
        margin-bottom: 12px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: var(--el-color-primary);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .job-icon {
          margin-right: 16px;
        }
        
        .job-info {
          flex: 1;
          min-width: 0;
          
          .job-name {
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .job-details {
            display: flex;
            gap: 16px;
            font-size: 13px;
            color: var(--el-text-color-secondary);
            
            @media (max-width: 480px) {
              flex-direction: column;
              gap: 2px;
            }
          }
        }
        
        .job-status {
          margin: 0 16px;
          text-align: center;
          min-width: 80px;
          
          .job-progress {
            margin-top: 8px;
            width: 60px;
          }
        }
        
        .job-time {
          min-width: 80px;
          text-align: right;
          font-size: 13px;
          color: var(--el-text-color-secondary);
          
          @media (max-width: 768px) {
            display: none;
          }
        }
        
        .job-actions {
          margin-left: 16px;
        }
      }
    }
  }
  
  .announcements-section {
    .announcements-list {
      .announcement-item {
        display: flex;
        align-items: flex-start;
        padding: 16px;
        margin-bottom: 12px;
        border-radius: 8px;
        border-left: 4px solid;
        
        &.info {
          background-color: var(--el-color-info-light-9);
          border-left-color: var(--el-color-info);
        }
        
        &.warning {
          background-color: var(--el-color-warning-light-9);
          border-left-color: var(--el-color-warning);
        }
        
        &.success {
          background-color: var(--el-color-success-light-9);
          border-left-color: var(--el-color-success);
        }
        
        &.error {
          background-color: var(--el-color-danger-light-9);
          border-left-color: var(--el-color-danger);
        }
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .announcement-icon {
          margin-right: 12px;
          margin-top: 2px;
        }
        
        .announcement-content {
          flex: 1;
          
          .announcement-title {
            font-weight: 600;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }
          
          .announcement-message {
            color: var(--el-text-color-regular);
            line-height: 1.5;
            margin-bottom: 8px;
          }
          
          .announcement-time {
            font-size: 12px;
            color: var(--el-text-color-placeholder);
          }
        }
        
        .announcement-actions {
          margin-left: 12px;
        }
      }
    }
  }
}

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