<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 targetType = progress.targetType === ProgressTargetType.CollectItem ? '收集' : '狩猎'
  const targetName = progress.targetItemName || (progress.targetType === ProgressTargetType.KillMonster ? '怪物' : '物品')
  return `${targetType} ${progress.currentCount}/${progress.targetCount} ${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('span', { class: 'card-title' }, props.mission.missionTitle),
        ]),
        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-difficulty' }, [
        h('span', { class: ['difficulty-badge', getDifficultyClass(props.mission.difficulty)] }, getDifficultyLabel(props.mission.difficulty)),
      ]),
      props.mission.progresses && props.mission.progresses.length > 0 && props.mission.status !== DailyMissionStatus.Pending
        ? h('div', { class: 'card-progress' }, [
            h('span', { class: 'progress-label' }, '进度:'),
            h('span', { class: 'progress-value' }, getProgressText(props.mission)),
          ])
        : null,
      h('div', { class: 'card-rewards' }, [
        h('span', { class: 'reward-item exp-reward' }, `✨${props.mission.expReward}`),
        ...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('button', { class: 'card-btn accept-btn', onClick: () => emit('accept') }, '接取')
          : canClaim(props.mission)
            ? h('button', { class: 'card-btn claim-btn', onClick: () => emit('claim') }, '领取')
            : props.mission.status === DailyMissionStatus.InProgress
              ? h('button', { class: 'card-btn disabled-btn', disabled: true }, '进行中')
              : props.mission.status === DailyMissionStatus.Claimed
                ? h('button', { class: 'card-btn disabled-btn', 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: rgba(255, 255, 255, 0.02);
  border: 1px solid;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.mission-card:hover {
  transform: translateY(-2px);
}

.purgatory-card {
  border: none;
}

.card-inner {
  padding: 16px;
}

.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: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  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: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

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

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

.card-desc {
  color: #888888;
  font-size: 0.8rem;
  line-height: 1.4;
}

.card-difficulty {
  display: flex;
  align-items: center;
}

.difficulty-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: 500;
}

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

.card-progress {
  display: flex;
  align-items: center;
  gap: 6px;
  background: rgba(255, 255, 255, 0.03);
  padding: 8px 10px;
  border-radius: 6px;
}

.progress-label {
  color: #666666;
  font-size: 0.75rem;
}

.progress-value {
  color: #22c55e;
  font-size: 0.8rem;
  font-weight: 500;
}

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

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

.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: 2px 6px;
  border-radius: 4px;
  font-size: 0.7rem;
}

.card-actions {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.card-btn {
  flex: 1;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 0.8rem;
  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>
