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

const router = useRouter()

const carouselItems: CarouselItem[] = [
  {
    title: "Custom Item",
    description: "A custom carousel item.",
    id: 1,
    icon: "circle",
  },
  {
    title: "Another Item",
    description: "Another carousel item.",
    id: 2,
    icon: "layers",
  },
  // Add more items as needed
];

const missions = ref<DailyMission[]>([])
const todayStats = ref({ claimed: 0, total: 0 })
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.Money:
      return '💰'
    case RewardType.Pill:
      return '💊'
    case RewardType.Equipment:
      return '⚔️'
    default:
      return '🎁'
  }
}

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
    if (data.length > 0) {
      todayStats.value = {
        claimed: data[0].todayClaimedCount,
        total: data[0].todayTotalCount
      }
    }
    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) {
    const errorMsg = error?.data?.message || error?.data || error?.message || '接取任务失败'
    showMsg(errorMsg, 'error')
  }
}

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

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

const handleMissionSelect = (mission: DailyMission) => {
  selectedMission.value = mission
}

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

const selectedMission = ref<DailyMission | null>(null)

const yesterdayMissions = computed(() => missions.value.filter(m => m.isFromYesterday && m.status === DailyMissionStatus.Completed))
const todayMissions = computed(() => missions.value.filter(m => !m.isFromYesterday))

const hasAnyMissions = computed(() => yesterdayMissions.value.length > 0 || todayMissions.value.length > 0)
</script>

<template>
  <div class="daily-mission-page">

    <Particles :particle-count="50" :particle-colors="['#ffffff', '#aaaaaa']" class="particles-bg" />

    <div class="page-container">

      <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="carousel-wrapper">
            <MissionCarousel :items="yesterdayMissions" :base-width="340" :card-height="220"
              @select="handleMissionSelect">
              <template #default="{ item }">
                <div class="mission-card-content">
                  <div class="card-header">
                    <span class="card-title">{{ item.missionTitle }}</span>
                    <span class="card-status" :class="getStatusClass(item.status)">
                      {{ getStatusText(item.status) }}
                    </span>
                  </div>
                  <div class="card-desc">{{ item.missionDescription }}</div>
                  <div class="card-time">
                    <span v-if="item.status === DailyMissionStatus.InProgress">
                      剩余: {{ remainingTimes[item.id] || formatRemainingTime(item.endTime) }}
                    </span>
                    <span v-else>
                      {{ item.spendTimeMinutes }}分钟
                    </span>
                  </div>
                  <div class="card-rewards">
                    <span class="reward-item exp-reward">✨{{ item.expReward }}</span>
                    <span v-for="(reward, idx) in item.rewards.slice(0, 2)" :key="idx" class="reward-item">
                      {{ getRewardIcon(reward.rewardType) }}{{ reward.count }}
                    </span>
                    <span v-if="item.rewards.length > 2" class="reward-more">+{{ item.rewards.length - 2 }}</span>
                  </div>
                  <div class="card-actions">
                    <button v-if="canAccept(item)" class="card-btn accept-btn" @click.stop="handleAccept(item)">
                      接取
                    </button>
                    <button v-if="canClaim(item)" class="card-btn claim-btn" @click.stop="handleClaim(item)">
                      领取
                    </button>
                    <button v-if="item.status === DailyMissionStatus.InProgress" class="card-btn disabled-btn" disabled>
                      挂机中
                    </button>
                    <button v-if="item.status === DailyMissionStatus.Claimed" class="card-btn disabled-btn" disabled>
                      已完成
                    </button>
                  </div>
                </div>
              </template>
</MissionCarousel>
</div>
</div> -->

        <div v-if="todayMissions.length > 0" class="mission-section">
          <div class="section-header">
            <span class="section-title">今日任务</span>
            <span class="section-badge">{{ todayStats.claimed }}/{{ todayStats.total }}</span>
          </div>
          <div class="carousel-wrapper">
            <MissionCarousel :items="todayMissions" :base-width="340" :card-height="180" @select="handleMissionSelect"
              :round="true" :loop="true">
              <template #default="{ item }">
                <div class="mission-card-content">
                  <div class="card-header">
                    <span class="card-title">{{ item.missionTitle }}</span>
                    <span class="card-status" :class="getStatusClass(item.status)">
                      {{ getStatusText(item.status) }}
                    </span>
                  </div>
                  <div class="card-desc">{{ item.missionDescription }}</div>
                  <div class="card-time">
                    <span v-if="item.status === DailyMissionStatus.InProgress">
                      剩余: {{ remainingTimes[item.id] || formatRemainingTime(item.endTime) }}
                    </span>
                    <span v-else>
                      {{ item.spendTimeMinutes }}分钟
                    </span>
                  </div>
                  <div class="card-rewards">
                    <span class="reward-item exp-reward">✨{{ item.expReward }}</span>
                    <span v-for="(reward, idx) in item.rewards.slice(0, 2)" :key="idx" class="reward-item">
                      {{ getRewardIcon(reward.rewardType) }}{{ reward.count }}
                    </span>
                    <span v-if="item.rewards.length > 2" class="reward-more">+{{ item.rewards.length - 2 }}</span>
                  </div>
                  <div class="card-actions">
                    <button v-if="canAccept(item)" class="card-btn accept-btn" @click.stop="handleAccept(item)">
                      接取
                    </button>
                    <button v-if="canClaim(item)" class="card-btn claim-btn" @click.stop="handleClaim(item)">
                      领取
                    </button>
                    <button v-if="item.status === DailyMissionStatus.InProgress" class="card-btn disabled-btn" disabled>
                      挂机中
                    </button>
                    <button v-if="item.status === DailyMissionStatus.Claimed" class="card-btn disabled-btn" disabled>
                      已完成
                    </button>
                  </div>
                </div>
              </template>
            </MissionCarousel>
          </div>
        </div>

        <div v-if="!hasAnyMissions" class="empty-state">
          <div class="empty-icon">📋</div>
          <div class="empty-text">今日暂无任务</div>
          <div class="empty-hint">请明日再来</div>
        </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;
}

.page-container {
  max-width: 480px;
  margin: 0 auto;
  position: relative;
  z-index: 10;
}

.particles-bg {
  position: fixed !important;
  top: 0;
  left: 0;
  width: 100% !important;
  height: 100% !important;
}

.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;
}

.carousel-wrapper {
  display: flex;
  justify-content: center;
}

.mission-card-content {
  width: 100%;
  height: 100%;
  padding: 12px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

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

.card-title {
  color: #ffffff;
  font-size: 0.9rem;
  font-weight: 600;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 8px;
}

.card-status {
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 0.65rem;
  font-weight: 500;
  white-space: nowrap;
}

.card-desc {
  color: #888888;
  font-size: 0.7rem;
  line-height: 1.3;
  margin-bottom: 6px;
  flex: 1;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-time {
  color: #ff8844;
  font-size: 0.7rem;
  margin-bottom: 8px;
}

.card-rewards {
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
  margin-bottom: 8px;
}

.card-rewards .reward-item {
  background: rgba(255, 136, 68, 0.1);
  border: 1px solid rgba(255, 136, 68, 0.2);
  color: #ff8844;
  padding: 1px 5px;
  border-radius: 4px;
  font-size: 0.65rem;
}

.card-rewards .exp-reward {
  background: rgba(255, 215, 0, 0.1);
  border-color: rgba(255, 215, 0, 0.3);
  color: #ffd700;
}

.reward-more {
  background: rgba(255, 255, 255, 0.1);
  color: #888888;
  padding: 1px 5px;
  border-radius: 4px;
  font-size: 0.65rem;
}

.card-actions {
  display: flex;
  gap: 6px;
}

.card-btn {
  flex: 1;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

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

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

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

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

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

.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;
}

.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>
