<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { dailyMissionApi, type DailyMission, DailyMissionStatus, RewardType } from '@/api/dailyMission'

const router = useRouter()

const missions = ref<DailyMission[]>([])
const loading = ref(false)
const message = ref('')
const showMessage = ref(false)

const showMsg = (text: string, type: 'success' | 'error' = 'success') => {
  message.value = text
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 2000)
}

const getStatusText = (status: DailyMissionStatus) => {
  switch (status) {
    case DailyMissionStatus.Pending:
      return '待接取'
    case DailyMissionStatus.InProgress:
      return '进行中'
    case DailyMissionStatus.Completed:
      return '待领取'
    case DailyMissionStatus.Claimed:
      return '已领取'
    default:
      return '未知'
  }
}

const getStatusClass = (status: DailyMissionStatus) => {
  switch (status) {
    case DailyMissionStatus.Pending:
      return 'status-pending'
    case DailyMissionStatus.InProgress:
      return 'status-progress'
    case DailyMissionStatus.Completed:
      return 'status-completed'
    case DailyMissionStatus.Claimed:
      return 'status-claimed'
    default:
      return ''
  }
}

const getRewardIcon = (type: RewardType) => {
  switch (type) {
    case RewardType.Exp:
      return '✨'
    case RewardType.Money:
      return '💰'
    case RewardType.Pill:
      return '💊'
    case RewardType.Equipment:
      return '⚔️'
    default:
      return '🎁'
  }
}

const formatTime = (dateStr?: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const formatRemainingTime = (endTime?: string) => {
  if (!endTime) return ''
  const end = new Date(endTime)
  const now = new Date()
  const diff = end.getTime() - now.getTime()
  if (diff <= 0) return '已完成'
  const minutes = Math.floor(diff / 60000)
  const seconds = Math.floor((diff % 60000) / 1000)
  return `${minutes}分${seconds}秒`
}

const remainingTimes = ref<Record<number, string>>({})
let timer: number | null = null

const updateRemainingTimes = () => {
  missions.value.forEach(mission => {
    if (mission.status === DailyMissionStatus.InProgress) {
      remainingTimes.value[mission.id] = formatRemainingTime(mission.endTime)
    }
  })
}

const canAccept = (mission: DailyMission) => mission.status === DailyMissionStatus.Pending
const canClaim = (mission: DailyMission) => mission.status === DailyMissionStatus.Completed

const loadMissions = async () => {
  loading.value = true
  try {
    const data = await dailyMissionApi.getList()
    missions.value = data
    updateRemainingTimes()
  } catch (error: any) {
    showMsg(error?.message || '加载任务失败', 'error')
  } finally {
    loading.value = false
  }
}

const handleAccept = async (mission: DailyMission) => {
  try {
    await dailyMissionApi.accept(mission.id)
    showMsg('接取任务成功')
    await loadMissions()
  } catch (error: any) {
    showMsg(error?.message || '接取任务失败', 'error')
  }
}

const handleClaim = async (mission: DailyMission) => {
  try {
    await dailyMissionApi.claim(mission.id)
    showMsg('领取奖励成功！')
    await loadMissions()
  } catch (error: any) {
    showMsg(error?.message || '领取奖励失败', 'error')
  }
}

const handleGoBack = () => {
  router.push('/game')
}

onMounted(() => {
  loadMissions()
  timer = window.setInterval(updateRemainingTimes, 1000)
})

const activeMissions = computed(() => missions.value.filter(m => m.status !== DailyMissionStatus.Claimed))
const yesterdayMissions = computed(() => activeMissions.value.filter(m => m.isFromYesterday))
const todayMissions = computed(() => activeMissions.value.filter(m => !m.isFromYesterday))
</script>

<template>
  <div class="daily-mission-page">
    <div class="page-header">
      <span class="back-btn" @click="handleGoBack">← 返回</span>
      <span class="title">每日任务</span>
      <span class="placeholder"></span>
    </div>

    <div v-if="showMessage" class="toast-message">
      {{ message }}
    </div>

    <div v-if="loading" class="loading">
      加载中...
    </div>

    <div v-else class="missions-content">
      <div v-if="yesterdayMissions.length > 0" class="mission-section yesterday-section">
        <div class="section-header">
          <span class="section-title">昨日任务</span>
          <span class="section-badge highlight">待领取</span>
        </div>
        <div class="mission-list">
          <div
            v-for="mission in yesterdayMissions"
            :key="mission.id"
            class="mission-card highlight"
          >
            <div class="mission-header">
              <span class="mission-name">{{ mission.missionTitle }}</span>
              <span class="mission-status" :class="getStatusClass(mission.status)">
                {{ getStatusText(mission.status) }}
              </span>
            </div>
            <div class="mission-desc">{{ mission.missionDescription }}</div>
            <div class="mission-time">
              <span v-if="mission.status === DailyMissionStatus.InProgress">
                剩余时间: {{ remainingTimes[mission.id] || formatRemainingTime(mission.endTime) }}
              </span>
              <span v-else-if="mission.status === DailyMissionStatus.Completed">
                已完成，请领取奖励
              </span>
              <span v-else>
                挂机时间: {{ mission.spendTimeMinutes }}分钟
              </span>
            </div>
            <div class="mission-rewards">
              <span class="rewards-label">奖励:</span>
              <span
                v-for="(reward, idx) in mission.rewards"
                :key="idx"
                class="reward-item"
              >
                {{ getRewardIcon(reward.rewardType) }}{{ reward.itemName || reward.rewardTypeName }}×{{ reward.count }}
              </span>
            </div>
            <div class="mission-actions">
              <button
                v-if="canAccept(mission)"
                class="action-btn accept-btn"
                @click="handleAccept(mission)"
              >
                接取任务
              </button>
              <button
                v-if="canClaim(mission)"
                class="action-btn claim-btn"
                @click="handleClaim(mission)"
              >
                领取奖励
              </button>
              <button
                v-if="mission.status === DailyMissionStatus.InProgress"
                class="action-btn disabled-btn"
                disabled
              >
                挂机中...
              </button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="todayMissions.length > 0" class="mission-section">
        <div class="section-header">
          <span class="section-title">今日任务</span>
          <span class="section-badge">{{ todayMissions.filter(m => m.status === DailyMissionStatus.Claimed).length }}/{{ todayMissions.length }}</span>
        </div>
        <div class="mission-list">
          <div
            v-for="mission in todayMissions"
            :key="mission.id"
            class="mission-card"
          >
            <div class="mission-header">
              <span class="mission-name">{{ mission.missionTitle }}</span>
              <span class="mission-status" :class="getStatusClass(mission.status)">
                {{ getStatusText(mission.status) }}
              </span>
            </div>
            <div class="mission-desc">{{ mission.missionDescription }}</div>
            <div class="mission-time">
              <span v-if="mission.status === DailyMissionStatus.InProgress">
                剩余时间: {{ remainingTimes[mission.id] || formatRemainingTime(mission.endTime) }}
              </span>
              <span v-else-if="mission.status === DailyMissionStatus.Completed">
                已完成，请领取奖励
              </span>
              <span v-else>
                挂机时间: {{ mission.spendTimeMinutes }}分钟
              </span>
            </div>
            <div class="mission-rewards">
              <span class="rewards-label">奖励:</span>
              <span
                v-for="(reward, idx) in mission.rewards"
                :key="idx"
                class="reward-item"
              >
                {{ getRewardIcon(reward.rewardType) }}{{ reward.itemName || reward.rewardTypeName }}×{{ reward.count }}
              </span>
            </div>
            <div class="mission-actions">
              <button
                v-if="canAccept(mission)"
                class="action-btn accept-btn"
                @click="handleAccept(mission)"
              >
                接取任务
              </button>
              <button
                v-if="canClaim(mission)"
                class="action-btn claim-btn"
                @click="handleClaim(mission)"
              >
                领取奖励
              </button>
              <button
                v-if="mission.status === DailyMissionStatus.InProgress"
                class="action-btn disabled-btn"
                disabled
              >
                挂机中...
              </button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="activeMissions.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">今日暂无任务</div>
        <div class="empty-hint">请明日再来</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.daily-mission-page {
  min-height: 100vh;
  background: #000000;
  padding: 20px;
  position: relative;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  margin-bottom: 20px;
}

.back-btn {
  color: #666666;
  font-size: 0.9rem;
  cursor: pointer;
  padding: 8px;
}

.back-btn:hover {
  color: #ffffff;
}

.title {
  color: #ffffff;
  font-size: 1.1rem;
  font-weight: 500;
}

.placeholder {
  width: 60px;
}

.toast-message {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.9);
  color: #000000;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 0.9rem;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

.loading {
  text-align: center;
  color: #666666;
  padding: 40px;
}

.missions-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.mission-section {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  padding: 16px;
}

.yesterday-section {
  background: rgba(255, 68, 68, 0.05);
  border-color: rgba(255, 68, 68, 0.2);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}

.section-title {
  color: #ffffff;
  font-size: 1rem;
  font-weight: 500;
}

.section-badge {
  background: rgba(255, 255, 255, 0.1);
  color: #888888;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.section-badge.highlight {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.mission-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.mission-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: 10px;
  padding: 14px;
  transition: all 0.3s ease;
}

.mission-card.highlight {
  background: rgba(255, 68, 68, 0.08);
  border-color: rgba(255, 68, 68, 0.3);
  box-shadow: 0 0 20px rgba(255, 68, 68, 0.1);
}

.mission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.mission-name {
  color: #ffffff;
  font-size: 0.95rem;
  font-weight: 500;
}

.mission-status {
  padding: 3px 10px;
  border-radius: 10px;
  font-size: 0.75rem;
}

.status-pending {
  background: rgba(100, 100, 100, 0.3);
  color: #888888;
}

.status-progress {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
}

.status-completed {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
}

.status-claimed {
  background: rgba(255, 255, 255, 0.1);
  color: #666666;
}

.mission-desc {
  color: #666666;
  font-size: 0.85rem;
  margin-bottom: 8px;
}

.mission-time {
  color: #ff8844;
  font-size: 0.8rem;
  margin-bottom: 10px;
}

.mission-rewards {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.rewards-label {
  color: #888888;
  font-size: 0.8rem;
}

.reward-item {
  background: rgba(255, 136, 68, 0.1);
  border: 1px solid rgba(255, 136, 68, 0.2);
  color: #ff8844;
  padding: 3px 8px;
  border-radius: 6px;
  font-size: 0.75rem;
}

.mission-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  flex: 1;
  padding: 10px 16px;
  border-radius: 8px;
  font-size: 0.85rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.accept-btn {
  background: linear-gradient(135deg, #ff8844 0%, #ff6644 100%);
  color: #ffffff;
}

.accept-btn:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 15px rgba(255, 136, 68, 0.3);
}

.claim-btn {
  background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
  color: #ffffff;
}

.claim-btn:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 15px rgba(34, 197, 94, 0.3);
}

.disabled-btn {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #555555;
  cursor: not-allowed;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 16px;
}

.empty-text {
  color: #ffffff;
  font-size: 1.1rem;
  margin-bottom: 8px;
}

.empty-hint {
  color: #666666;
  font-size: 0.9rem;
}
</style>
