<template>
  <div class="profile-view">
    <!-- 頁面標題 -->
    <div class="page-header">
      <h1 class="page-title">個人設定</h1>
    </div>

    <!-- 用戶資訊 -->
    <div class="content-card">
      <div class="card-header">
        <h3 class="card-title">基本資訊</h3>
      </div>
      <div class="card-body">
        <div class="user-profile">
          <div class="avatar-section">
            <div class="user-avatar">
              <div class="avatar-circle">
                {{ userInitials }}
              </div>
            </div>
            <div class="user-basic-info">
              <h3 class="user-name">{{ authStore.userName }}</h3>
              <p class="user-email">{{ authStore.userEmail }}</p>
              <el-tag v-if="authStore.isAdmin" type="warning" size="small">
                管理員
              </el-tag>
            </div>
          </div>
          
          <div class="user-details">
            <div class="detail-row">
              <div class="detail-item">
                <div class="detail-label">AD 帳號</div>
                <div class="detail-value">{{ authStore.user?.username }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">部門</div>
                <div class="detail-value">{{ authStore.department || '未設定' }}</div>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <div class="detail-label">最後登入</div>
                <div class="detail-value">{{ formatTime(authStore.user?.last_login) }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">權限等級</div>
                <div class="detail-value">{{ authStore.isAdmin ? '管理員' : '一般使用者' }}</div>
              </div>
            </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" @click="refreshStats" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      <div class="card-body">
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon primary">
              <el-icon><Files /></el-icon>
            </div>
            <div class="stat-value">{{ userStats.totalJobs }}</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">{{ userStats.completedJobs }}</div>
            <div class="stat-label">已完成</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon warning">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-value">${{ userStats.totalCost.toFixed(4) }}</div>
            <div class="stat-label">總成本</div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon info">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-value">{{ userStats.avgProcessingTime }}</div>
            <div class="stat-label">平均處理時間</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 偏好設定 -->
    <div class="content-card">
      <div class="card-header">
        <h3 class="card-title">偏好設定</h3>
      </div>
      <div class="card-body">
        <el-form :model="preferences" label-width="120px" size="default">
          <el-form-item label="預設來源語言">
            <el-select v-model="preferences.defaultSourceLang" style="width: 200px">
              <el-option label="自動偵測" value="auto" />
              <el-option label="繁體中文" value="zh-TW" />
              <el-option label="簡體中文" value="zh-CN" />
              <el-option label="英文" value="en" />
              <el-option label="日文" value="ja" />
              <el-option label="韓文" value="ko" />
              <el-option label="越南文" value="vi" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="預設目標語言">
            <el-select 
              v-model="preferences.defaultTargetLangs" 
              multiple 
              style="width: 300px"
              placeholder="請選擇常用的目標語言"
            >
              <el-option label="英文" value="en" />
              <el-option label="越南文" value="vi" />
              <el-option label="繁體中文" value="zh-TW" />
              <el-option label="簡體中文" value="zh-CN" />
              <el-option label="日文" value="ja" />
              <el-option label="韓文" value="ko" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="通知設定">
            <el-checkbox-group v-model="preferences.notifications">
              <el-checkbox label="email" name="notifications">
                翻譯完成時發送郵件通知
              </el-checkbox>
              <el-checkbox label="browser" name="notifications">
                瀏覽器桌面通知
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="介面語言">
            <el-select v-model="preferences.interfaceLang" style="width: 150px">
              <el-option label="繁體中文" value="zh-TW" />
              <el-option label="English" value="en" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="savePreferences" :loading="saving">
              儲存設定
            </el-button>
            <el-button @click="resetPreferences">
              重置為預設值
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="content-card">
      <div class="card-header">
        <h3 class="card-title">快速操作</h3>
      </div>
      <div class="card-body">
        <div class="quick-actions">
          <el-button @click="$router.push('/upload')">
            <el-icon><Upload /></el-icon>
            上傳新檔案
          </el-button>
          
          <el-button @click="$router.push('/jobs')">
            <el-icon><List /></el-icon>
            查看我的任務
          </el-button>
          
          <el-button @click="$router.push('/history')">
            <el-icon><Clock /></el-icon>
            瀏覽歷史記錄
          </el-button>
          
          <el-button @click="downloadUserData" :loading="downloading">
            <el-icon><Download /></el-icon>
            匯出我的資料
          </el-button>
        </div>
      </div>
    </div>

    <!-- 帳號安全 -->
    <div class="content-card">
      <div class="card-header">
        <h3 class="card-title">帳號安全</h3>
      </div>
      <div class="card-body">
        <div class="security-info">
          <div class="security-item">
            <div class="security-icon">
              <el-icon><Key /></el-icon>
            </div>
            <div class="security-content">
              <div class="security-title">密碼管理</div>
              <div class="security-description">
                本系統使用公司 AD 帳號認證，如需變更密碼請聯繫 IT 部門
              </div>
            </div>
          </div>
          
          <div class="security-item">
            <div class="security-icon">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="security-content">
              <div class="security-title">登入記錄</div>
              <div class="security-description">
                最後登入時間: {{ formatTime(authStore.user?.last_login) }}
              </div>
              <el-button type="text" @click="viewLoginHistory">
                查看詳細記錄
              </el-button>
            </div>
          </div>
          
          <div class="security-item">
            <div class="security-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="security-content">
              <div class="security-title">權限說明</div>
              <div class="security-description">
                {{ authStore.isAdmin 
                  ? '您擁有系統管理員權限，可以查看所有用戶的任務和系統統計' 
                  : '您為一般使用者，只能查看和管理自己的翻譯任務' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useJobsStore } from '@/stores/jobs'
import { ElMessage } from 'element-plus'
import {
  Refresh, Files, SuccessFilled, Money, Clock, Upload, List,
  Download, Key, Lock, UserFilled
} from '@element-plus/icons-vue'

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

// 響應式數據
const loading = ref(false)
const saving = ref(false)
const downloading = ref(false)

// 偏好設定
const preferences = reactive({
  defaultSourceLang: 'auto',
  defaultTargetLangs: ['en'],
  notifications: ['email'],
  interfaceLang: 'zh-TW'
})

// 計算屬性
const userInitials = computed(() => {
  const name = authStore.userName || authStore.user?.username || 'U'
  return name.charAt(0).toUpperCase()
})

const userStats = computed(() => {
  const jobs = jobsStore.jobs
  const completedJobs = jobs.filter(job => job.status === 'COMPLETED')
  const totalCost = jobs.reduce((sum, job) => sum + (job.total_cost || 0), 0)
  
  // 計算平均處理時間
  const processingTimes = completedJobs
    .filter(job => job.processing_started_at && job.completed_at)
    .map(job => {
      const start = new Date(job.processing_started_at)
      const end = new Date(job.completed_at)
      return end - start
    })
  
  let avgProcessingTime = '無資料'
  if (processingTimes.length > 0) {
    const avgMs = processingTimes.reduce((sum, time) => sum + time, 0) / processingTimes.length
    const minutes = Math.floor(avgMs / 60000)
    const seconds = Math.floor((avgMs % 60000) / 1000)
    avgProcessingTime = `${minutes}分${seconds}秒`
  }
  
  return {
    totalJobs: jobs.length,
    completedJobs: completedJobs.length,
    totalCost,
    avgProcessingTime
  }
})

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

const savePreferences = async () => {
  saving.value = true
  try {
    // 儲存到本地存儲
    localStorage.setItem('userPreferences', JSON.stringify(preferences))
    
    // 同時更新翻譯設定的預設值
    localStorage.setItem('translation_settings', JSON.stringify({
      sourceLanguage: preferences.defaultSourceLang,
      targetLanguages: preferences.defaultTargetLangs
    }))
    
    ElMessage.success('設定已儲存')
  } catch (error) {
    console.error('儲存設定失敗:', error)
    ElMessage.error('儲存設定失敗')
  } finally {
    saving.value = false
  }
}

const resetPreferences = () => {
  Object.assign(preferences, {
    defaultSourceLang: 'auto',
    defaultTargetLangs: ['en'],
    notifications: ['email'],
    interfaceLang: 'zh-TW'
  })
  ElMessage.info('設定已重置為預設值')
}

const downloadUserData = async () => {
  downloading.value = true
  try {
    const userData = {
      userInfo: {
        username: authStore.user?.username,
        displayName: authStore.userName,
        email: authStore.userEmail,
        department: authStore.department,
        isAdmin: authStore.isAdmin
      },
      jobs: jobsStore.jobs,
      statistics: userStats.value,
      preferences: preferences,
      exportTime: new Date().toISOString()
    }
    
    const dataStr = JSON.stringify(userData, null, 2)
    const blob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `我的翻譯資料_${new Date().toISOString().slice(0, 10)}.json`
    link.click()
    
    URL.revokeObjectURL(url)
    ElMessage.success('資料匯出完成')
  } catch (error) {
    console.error('匯出資料失敗:', error)
    ElMessage.error('匯出資料失敗')
  } finally {
    downloading.value = false
  }
}

const viewLoginHistory = () => {
  ElMessage.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', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命週期
onMounted(async () => {
  // 載入用戶偏好設定
  try {
    const savedPreferences = localStorage.getItem('userPreferences')
    if (savedPreferences) {
      Object.assign(preferences, JSON.parse(savedPreferences))
    }
  } catch (error) {
    console.error('載入偏好設定失敗:', error)
  }
  
  // 載入統計資料
  await refreshStats()
})
</script>

<style lang="scss" scoped>
.profile-view {
  .user-profile {
    .avatar-section {
      display: flex;
      align-items: center;
      gap: 24px;
      margin-bottom: 32px;
      
      .user-avatar {
        .avatar-circle {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          background: linear-gradient(45deg, var(--el-color-primary), var(--el-color-primary-light-3));
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 24px;
          font-weight: bold;
        }
      }
      
      .user-basic-info {
        .user-name {
          margin: 0 0 8px 0;
          color: var(--el-text-color-primary);
          font-size: 20px;
        }
        
        .user-email {
          margin: 0 0 8px 0;
          color: var(--el-text-color-secondary);
          font-size: 14px;
        }
      }
    }
    
    .user-details {
      .detail-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 32px;
        margin-bottom: 16px;
        
        @media (max-width: 768px) {
          grid-template-columns: 1fr;
          gap: 16px;
        }
        
        .detail-item {
          .detail-label {
            font-size: 13px;
            color: var(--el-text-color-secondary);
            margin-bottom: 4px;
          }
          
          .detail-value {
            font-size: 14px;
            color: var(--el-text-color-primary);
            font-weight: 500;
          }
        }
      }
    }
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .quick-actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
  }
  
  .security-info {
    .security-item {
      display: flex;
      align-items: flex-start;
      gap: 16px;
      padding: 16px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      &:last-child {
        border-bottom: none;
      }
      
      .security-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
      }
      
      .security-content {
        flex: 1;
        
        .security-title {
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
        
        .security-description {
          color: var(--el-text-color-regular);
          line-height: 1.5;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>