<script setup lang="ts">
import { ref, computed, onMounted, defineComponent, type PropType, h } from 'vue'
import { useRouter } from 'vue-router'
import { dailyMissionApi, type DailyMission, DailyMissionStatus, RewardType, MissionType, MissionDifficulty, ProgressTargetType } from '@/api/dailyMission'
import Particles from '@/components/Particles/Particles.vue'
import ElectricBorder from '@/components/ElectricBorder/ElectricBorder.vue'
import collectionIcon from '@/assets/images/collection.svg?raw'
import huntingNormalIcon from '@/assets/images/hunting.svg?raw'

const router = useRouter()

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 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
      }
    }
  } 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')
}

onMounted(() => {
  loadMissions()
})

const activeMissions = computed(() => missions.value.filter(m => !m.isFromYesterday))
const hasAnyMissions = computed(() => activeMissions.value.length > 0)

const getMissionTypeClass = (type: MissionType, difficulty: MissionDifficulty) => {
  if (type === MissionType.Collection) {
    return 'mission-collection'
  }
  if (difficulty === MissionDifficulty.Purgatory) {
    return 'mission-hunting-purgatory'
  }
  if (difficulty === MissionDifficulty.Hard) {
    return 'mission-hunting-hard'
  }
  return 'mission-hunting-normal'
}

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 getDifficultyLabel = (difficulty: MissionDifficulty) => {
  switch (difficulty) {
    case MissionDifficulty.Normal: return '普通'
    case MissionDifficulty.Hard: return '困难'
    case MissionDifficulty.Purgatory: return '炼狱'
    default: return ''
  }
}

const getDifficultyClass = (difficulty: MissionDifficulty) => {
  switch (difficulty) {
    case MissionDifficulty.Normal: return 'difficulty-normal'
    case MissionDifficulty.Hard: return 'difficulty-hard'
    case MissionDifficulty.Purgatory: return 'difficulty-purgatory'
    default: return ''
  }
}

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

const getProgressText = (mission: DailyMission) => {
  if (!mission.progresses || mission.progresses.length === 0) return ''
  const progress = mission.progresses[0]
  const targetTypeLabel = progress.targetType === ProgressTargetType.CollectItem ? '收集' 
    : progress.targetType === ProgressTargetType.KillMonster ? '击杀'
    : progress.targetType === ProgressTargetType.Fish ? '钓鱼'
    : progress.targetType === ProgressTargetType.ConsumeItem ? '消耗'
    : progress.targetType === ProgressTargetType.Custom ? '挂机'
    : '完成'
  const targetName = progress.targetItemName || (progress.targetType === ProgressTargetType.KillMonster ? '怪物' : '物品')
  // Pending状态显示目标数量，进行中/已完成显示当前进度
  const displayCount = mission.status === DailyMissionStatus.Pending 
    ? `0/${progress.targetCount}` 
    : `${progress.currentCount}/${progress.targetCount}`
  return `${targetTypeLabel} ${displayCount} ${targetName}`
}

const getMissionIcon = (type: MissionType, difficulty: MissionDifficulty) => {
  if (type === MissionType.Collection) {
    return collectionIcon
  }
  // For hunting, use different filters based on difficulty
  return huntingNormalIcon
}

const getMissionIconFilter = (type: MissionType, difficulty: MissionDifficulty) => {
  if (type === MissionType.Collection) {
    return 'none'
  }
  switch (difficulty) {
    case MissionDifficulty.Purgatory:
      return 'hue-rotate(-10deg) saturate(1.5) brightness(0.8)'
    case MissionDifficulty.Hard:
      return 'hue-rotate(-30deg) saturate(1.2)'
    default:
      return 'none'
  }
}

const MissionCardContent = defineComponent({
  name: 'MissionCardContent',
  props: {
    mission: {
      type: Object as PropType<DailyMission>,
      required: true
    }
  },
  emits: ['accept', 'claim'],
  setup(props, { emit }) {
    return () => h('div', { class: 'mission-card-content' }, [
      h('div', { class: 'card-header' }, [
        h('div', { class: 'card-title-row' }, [
          h('div', { class: 'card-icon', style: `filter: ${getMissionIconFilter(props.mission.missionType, props.mission.difficulty)}`, innerHTML: getMissionIcon(props.mission.missionType, props.mission.difficulty) }),
          h('div', { class: 'title-stack' }, [
            h('span', { class: 'card-title' }, props.mission.missionTitle),
            h('span', { class: 'card-subtitle' }, props.mission.missionName),
          ]),
        ]),
        h('span', { class: ['card-status', getStatusClass(props.mission.status)] }, getStatusText(props.mission.status)),
      ]),
      h('div', { class: 'card-desc' }, props.mission.missionDescription),
      h('div', { class: 'card-meta-row' }, [
        h('span', { class: ['difficulty-badge', getDifficultyClass(props.mission.difficulty)] }, getDifficultyLabel(props.mission.difficulty)),
        h('span', { class: 'time-badge' }, `预计 ${props.mission.spendTimeMinutes} 分钟`),
      ]),
      props.mission.progresses && props.mission.progresses.length > 0
        ? h('div', { class: 'objective-panel' }, [
            h('span', { class: 'objective-label' }, '任务目标'),
            h('span', { class: 'objective-value' }, getProgressText(props.mission)),
          ])
        : null,
      h('div', { class: 'reward-section' }, [
        h('div', { class: 'section-label' }, '任务奖励'),
        h('div', { class: 'card-rewards' }, [
          h('span', { class: 'reward-item exp-reward' }, `✨ ${props.mission.expReward}`),
          h('span', { class: 'reward-item money-reward' }, `💰 ${props.mission.moneyReward}`),
          ...props.mission.rewards.slice(0, 2).map((reward: any) =>
            h('span', { class: 'reward-item' }, `${getRewardIcon(reward.rewardType)} ${reward.count}`)
          ),
          props.mission.rewards.length > 2
            ? h('span', { class: 'reward-more' }, `+${props.mission.rewards.length - 2}`)
            : null,
        ]),
      ]),
      h('div', { class: 'card-actions' }, [
        !canAccept(props.mission)
          ? h('span', { class: 'action-hint' }, canClaim(props.mission)
            ? '任务已完成，领取奖励'
            : props.mission.status === DailyMissionStatus.InProgress
              ? '任务正在进行中'
              : '奖励已领取'
          )
          : null,
        canAccept(props.mission)
          ? h('button', { class: 'card-btn accept-btn', type: 'button', onClick: () => emit('accept') }, [
              h('span', { class: 'btn-label' }, '准备好后即可接取'),
              h('span', { class: 'btn-arrow' }, '›'),
            ])
          : canClaim(props.mission)
            ? h('button', { class: 'card-btn claim-btn', type: 'button', onClick: () => emit('claim') }, [
                h('span', { class: 'btn-label' }, '领取奖励'),
                h('span', { class: 'btn-arrow' }, '›'),
              ])
            : props.mission.status === DailyMissionStatus.InProgress
              ? h('button', { class: 'card-btn disabled-btn', type: 'button', disabled: true }, '进行中')
              : props.mission.status === DailyMissionStatus.Claimed
                ? h('button', { class: 'card-btn disabled-btn', type: 'button', disabled: true }, '已完成')
                : null,
      ]),
    ])
  }
})
</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="activeMissions.length > 0" class="stats-bar">
          <span class="stats-text">今日进度: {{ todayStats.claimed }}/{{ todayStats.total }}</span>
        </div>

        <div v-if="hasAnyMissions" class="mission-list">
          <template v-for="mission in activeMissions" :key="mission.id">
            <ElectricBorder
              v-if="mission.difficulty === MissionDifficulty.Purgatory"
              color="#dc2626"
              :speed="1.2"
              :chaos="1.5"
              :thickness="2"
              class="mission-card purgatory-card"
            >
              <div class="card-inner">
                <component 
                  :is="MissionCardContent" 
                  :mission="mission" 
                  @accept="handleAccept(mission)"
                  @claim="handleClaim(mission)"
                />
              </div>
            </ElectricBorder>
            <div
              v-else
              class="mission-card"
              :class="getMissionTypeClass(mission.missionType, mission.difficulty)"
            >
              <div class="card-inner">
                <component 
                  :is="MissionCardContent" 
                  :mission="mission"
                  @accept="handleAccept(mission)"
                  @claim="handleClaim(mission)"
                />
              </div>
            </div>
          </template>
        </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: 16px;
}

.stats-bar {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 12px 16px;
  text-align: center;
}

.stats-text {
  color: #888888;
  font-size: 0.9rem;
}

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

.mission-card {
  background:
    radial-gradient(circle at top left, rgba(255, 136, 68, 0.08), transparent 34%),
    rgba(255, 255, 255, 0.025);
  border: 1px solid;
  border-radius: 18px;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
}

.mission-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 18px 34px rgba(0, 0, 0, 0.28);
}

.purgatory-card {
  border: none;
}

.card-inner {
  padding: 18px;
}

.mission-collection {
  border-color: rgba(34, 197, 94, 0.3);
}

.mission-hunting-normal {
  border-color: rgba(239, 68, 68, 0.3);
}

.mission-hunting-hard {
  border-color: rgba(249, 115, 22, 0.4);
}

.mission-hunting-purgatory {
  border-color: rgba(220, 38, 38, 0.5);
}

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

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

.card-title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.card-icon {
  width: 34px;
  height: 34px;
  flex: 0 0 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.06);
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);
}

.card-icon :deep(svg) {
  width: 100%;
  height: 100%;
}

.title-stack {
  display: flex;
  flex-direction: column;
  gap: 3px;
  min-width: 0;
}

.card-title {
  color: #ffffff;
  font-size: 1.05rem;
  font-weight: 700;
  letter-spacing: 0.02em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-subtitle {
  color: #777777;
  font-size: 0.72rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-status {
  padding: 5px 10px;
  border-radius: 999px;
  font-size: 0.72rem;
  font-weight: 700;
  white-space: nowrap;
  letter-spacing: 0.04em;
}

.card-desc {
  color: #aaaaaa;
  font-size: 0.84rem;
  line-height: 1.55;
}

.card-meta-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.difficulty-badge {
  padding: 4px 10px;
  border-radius: 999px;
  font-size: 0.72rem;
  font-weight: 700;
}

.time-badge {
  padding: 4px 10px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  color: #9ca3af;
  font-size: 0.72rem;
  font-weight: 600;
}

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

.difficulty-hard {
  background: rgba(249, 115, 22, 0.2);
  color: #f97316;
}

.difficulty-purgatory {
  background: rgba(220, 38, 38, 0.3);
  color: #fca5a5;
}

.objective-panel {
  display: flex;
  flex-direction: column;
  gap: 5px;
  background: linear-gradient(135deg, rgba(34, 197, 94, 0.12), rgba(255, 255, 255, 0.035));
  border: 1px solid rgba(34, 197, 94, 0.18);
  padding: 11px 12px;
  border-radius: 12px;
}

.objective-label {
  color: #86efac;
  font-size: 0.72rem;
  font-weight: 700;
  letter-spacing: 0.08em;
}

.objective-value {
  color: #ffffff;
  font-size: 0.9rem;
  font-weight: 700;
}

.reward-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.section-label {
  color: #777777;
  font-size: 0.72rem;
  font-weight: 700;
  letter-spacing: 0.08em;
}

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

.reward-item {
  background: rgba(255, 136, 68, 0.1);
  border: 1px solid rgba(255, 136, 68, 0.2);
  color: #ff8844;
  padding: 5px 9px;
  border-radius: 999px;
  font-size: 0.74rem;
  font-weight: 700;
}

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

.money-reward {
  background: rgba(34, 197, 94, 0.1);
  border-color: rgba(34, 197, 94, 0.3);
  color: #22c55e;
}

.reward-more {
  background: rgba(255, 255, 255, 0.1);
  color: #888888;
  padding: 5px 9px;
  border-radius: 999px;
  font-size: 0.74rem;
  font-weight: 700;
}

:deep(.card-actions) {
  display: flex;
  flex-direction: column;
  gap: 9px;
  margin-top: 6px;
  padding-top: 14px;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
}

:deep(.action-hint) {
  color: #777777;
  font-size: 0.75rem;
  text-align: center;
}

:deep(.card-btn) {
  width: 100%;
  min-height: 50px;
  padding: 0 18px;
  border-radius: 16px;
  font-size: 0.95rem;
  font-weight: 800;
  cursor: pointer;
  transition: transform 0.18s ease, box-shadow 0.18s ease, filter 0.18s ease;
  border: 1px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  letter-spacing: 0.08em;
}

:deep(.btn-label) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

:deep(.card-btn:active:not(:disabled)) {
  transform: scale(0.98);
}

:deep(.btn-arrow) {
  font-size: 1.3rem;
  line-height: 1;
  transform: translateY(-1px);
}

:deep(.card-btn.accept-btn) {
  background: linear-gradient(135deg, #facc15 0%, #ff8844 45%, #ef4444 100%);
  border-color: rgba(255, 214, 102, 0.55);
  color: #ffffff;
  box-shadow:
    0 10px 24px rgba(255, 136, 68, 0.26),
    inset 0 1px 0 rgba(255, 255, 255, 0.22);
  text-shadow: 0 1px 8px rgba(0, 0, 0, 0.35);
}

:deep(.card-btn.accept-btn .btn-label) {
  font-size: 1rem;
  font-weight: 900;
  color: #ffffff;
  letter-spacing: 0.1em;
}

:deep(.card-btn.accept-btn:hover) {
  transform: translateY(-1px);
  filter: brightness(1.08);
  box-shadow:
    0 14px 30px rgba(255, 136, 68, 0.38),
    0 0 20px rgba(250, 204, 21, 0.22),
    inset 0 1px 0 rgba(255, 255, 255, 0.26);
}

:deep(.card-btn.claim-btn) {
  background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
  border-color: rgba(134, 239, 172, 0.4);
  color: #ffffff;
  box-shadow:
    0 10px 24px rgba(34, 197, 94, 0.24),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
}

:deep(.card-btn.claim-btn:hover) {
  transform: translateY(-1px);
  filter: brightness(1.08);
  box-shadow:
    0 14px 30px rgba(34, 197, 94, 0.36),
    0 0 18px rgba(134, 239, 172, 0.18),
    inset 0 1px 0 rgba(255, 255, 255, 0.24);
}

:deep(.card-btn.disabled-btn) {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #6b7280;
  cursor: not-allowed;
  box-shadow: none;
}

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