<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import QuizCard from '../components/QuizCard.vue'
import { api, type QuizQuestion, type QuizTrack } from '../api/request'
import {
  clearQuizSession,
  loadQuizSession,
  submitQuizAnswer,
  useQuizAutoSave,
  type QuizSessionSnapshot,
} from '../composables/useQuizSession'
import { useQuizTimer } from '../composables/useQuizTimer'

const route = useRoute()
const track = computed<QuizTrack>(() =>
  route.query.track === 'book' ? 'book' : 'accumulation'
)
const pageTitle = computed(() =>
  track.value === 'book' ? '词书每日训练' : '积累每日训练'
)

const { startQuestionTimer, consumeDurationSeconds } = useQuizTimer()

const questions = ref<QuizQuestion[]>([])
const currentIndex = ref(0)
const selected = ref('')
const showResult = ref(false)
const isCorrect = ref(false)
const loading = ref(true)
const finished = ref(false)
const sessionCorrect = ref(0)
const sessionWrong = ref(0)
const empty = ref(false)
const restored = ref(false)

const current = () => questions.value[currentIndex.value]

function buildSnapshot(): QuizSessionSnapshot | null {
  if (!questions.value.length) return null
  return {
    questions: questions.value,
    currentIndex: currentIndex.value,
    sessionCorrect: sessionCorrect.value,
    sessionWrong: sessionWrong.value,
    finished: finished.value,
    selected: selected.value,
    showResult: showResult.value,
    isCorrect: isCorrect.value,
  }
}

const { persist, flushPending } = useQuizAutoSave('daily', buildSnapshot, {}, track.value)

function applySnapshot(snap: QuizSessionSnapshot) {
  questions.value = snap.questions
  currentIndex.value = snap.currentIndex
  sessionCorrect.value = snap.sessionCorrect
  sessionWrong.value = snap.sessionWrong
  finished.value = snap.finished
  selected.value = snap.selected ?? ''
  showResult.value = snap.showResult ?? false
  isCorrect.value = snap.isCorrect ?? false
}

onMounted(async () => {
  try {
    const saved = loadQuizSession('daily', track.value)
    if (saved && !saved.finished) {
      applySnapshot(saved)
      restored.value = true
      await flushPending()
    } else {
      clearQuizSession('daily', track.value)
      const { data } = await api.dailyQuiz(track.value)
      questions.value = data.questions
      if (data.questions.length === 0) {
        empty.value = true
      } else {
        persist()
      }
    }
  } finally {
    loading.value = false
    if (current() && !showResult.value) startQuestionTimer()
  }
})

watch(currentIndex, () => {
  if (!loading.value && !finished.value && current() && !showResult.value) {
    startQuestionTimer()
  }
})

async function onSelect(answer: string) {
  if (showResult.value) return
  selected.value = answer
  const q = current()
  if (!q) return

  const payload = {
    word_id: q.word_id,
    question_type: q.question_type,
    user_answer: answer,
    correct_answer: q.correct_answer,
    duration_seconds: consumeDurationSeconds(),
  }

  const result = await submitQuizAnswer('daily', payload, track.value)
  if (result.ok && result.is_correct !== undefined) {
    isCorrect.value = result.is_correct
  } else {
    isCorrect.value = answer === q.correct_answer
  }
  if (isCorrect.value) sessionCorrect.value++
  else sessionWrong.value++

  showResult.value = true
  persist()
}

function nextQuestion() {
  if (currentIndex.value >= questions.value.length - 1) {
    finished.value = true
    clearQuizSession('daily')
    return
  }
  currentIndex.value++
  selected.value = ''
  showResult.value = false
  isCorrect.value = false
  startQuestionTimer()
  persist()
}

const accuracy = () => {
  const total = sessionCorrect.value + sessionWrong.value
  return total ? Math.round((sessionCorrect.value / total) * 100) : 0
}
</script>

<template>
  <div class="page quiz-page">
    <h1 class="page-title">{{ pageTitle }}</h1>

    <p v-if="restored && !loading && !finished && !empty" class="quiz-hint">
      已恢复上次进度
    </p>

    <p v-if="loading" class="quiz-muted">加载中…</p>

    <div v-else-if="empty" class="quiz-empty">
      <p v-if="track === 'book'" class="quiz-muted">请先在首页选择词书，或今日暂无待练词目</p>
      <p v-else class="quiz-muted">积累词库至少需 4 个单词</p>
      <router-link v-if="track === 'book'" to="/" class="quiz-link">回首页选书</router-link>
      <router-link v-else to="/translate" class="quiz-link">去添加</router-link>
    </div>

    <div v-else-if="finished" class="quiz-done">
      <p class="quiz-done-rate">{{ accuracy() }}%</p>
      <p class="quiz-done-meta">
        {{ sessionCorrect }} 对 · {{ sessionWrong }} 错 · 共
        {{ sessionCorrect + sessionWrong }} 题
      </p>
      <router-link to="/" class="btn btn-primary quiz-done-btn">完成</router-link>
    </div>

    <template v-else-if="current()">
      <QuizCard
        :question="current()!"
        :index="currentIndex"
        :total="questions.length"
        :selected="selected"
        :show-result="showResult"
        :is-correct="isCorrect"
        @select="onSelect"
      />
      <button
        v-if="showResult"
        class="btn btn-primary quiz-next"
        @click="nextQuestion"
      >
        {{ currentIndex >= questions.length - 1 ? '结果' : '下一题' }}
      </button>
    </template>
  </div>
</template>

<style scoped>
.quiz-hint,
.quiz-muted {
  font-size: 13px;
  color: var(--muted);
  margin: -12px 0 16px;
}

.quiz-empty {
  text-align: center;
  padding: 48px 0;
}

.quiz-link {
  display: inline-block;
  margin-top: 8px;
  font-size: 15px;
  color: var(--primary);
}

.quiz-done {
  text-align: center;
  padding: 40px 0 16px;
}

.quiz-done-rate {
  font-size: 48px;
  font-weight: 700;
  color: var(--primary);
  margin: 0;
  line-height: 1.1;
}

.quiz-done-meta {
  font-size: 14px;
  color: var(--muted);
  margin: 12px 0 28px;
}

.quiz-done-btn {
  max-width: 200px;
  margin: 0 auto;
}

.quiz-next {
  margin-top: 16px;
}
</style>
