<script setup lang="ts">
import { computed, onMounted, reactive, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchBankAttemptHistory, fetchBankTags, startBankAttempt, startPaperAttempt } from '@/api/quiz'
import type { PageMeta, Paper, QuestionBank, QuizAttemptHistory } from '@/types/api'
import { fetchResources } from '@/api/quiz'

const router = useRouter()
const banks = shallowRef<QuestionBank[]>([])
const papers = shallowRef<Paper[]>([])
const loading = shallowRef(false)
const randomDialogVisible = shallowRef(false)
const historyDialogVisible = shallowRef(false)
const randomBank = shallowRef<QuestionBank | null>(null)
const historyBank = shallowRef<QuestionBank | null>(null)
const historyAttempts = shallowRef<QuizAttemptHistory[]>([])
const historyMeta = shallowRef<PageMeta>({ current_page: 1, per_page: 10, total: 0, last_page: 1 })
const historyPage = shallowRef(1)
const historyPageSize = shallowRef(10)
const historyLoading = shallowRef(false)
const tags = shallowRef<Array<{ id: number; name: string }>>([])
const randomForm = reactive({
  limit: 20,
  types: [] as string[],
  tag_ids: [] as number[],
})

const typeOptions = [
  { label: '单选', value: 'single' },
  { label: '多选', value: 'multiple' },
  { label: '判断', value: 'judge' },
  { label: '填空', value: 'blank' },
]

const randomTitle = computed(() => randomBank.value ? `${randomBank.value.name} - 随机刷题` : '随机刷题')
const historyTitle = computed(() => historyBank.value ? `${historyBank.value.name} - 历史回顾` : '历史回顾')

async function loadResources() {
  loading.value = true
  try {
    const response = await fetchResources()
    const resources = response.data as { banks: QuestionBank[]; papers?: Paper[] }
    banks.value = resources.banks
    papers.value = resources.papers ?? []
  } finally {
    loading.value = false
  }
}

async function start(bank: QuestionBank, mode: string, extra: Record<string, unknown> = {}) {
  const response = await startBankAttempt(bank.id, { mode, ...extra })
  await router.push(`/quiz/${response.data.id}`)
}

async function openRandom(bank: QuestionBank) {
  randomBank.value = bank
  randomForm.limit = Math.min(Math.max(bank.questions_count || 20, 1), 20)
  randomForm.types = []
  randomForm.tag_ids = []
  tags.value = (await fetchBankTags(bank.id)).data as Array<{ id: number; name: string }>
  randomDialogVisible.value = true
}

async function submitRandom() {
  if (!randomBank.value) return
  await start(randomBank.value, 'random', {
    limit: randomForm.limit,
    type: randomForm.types,
    tag_ids: randomForm.tag_ids,
  })
}

async function reviewWrong(bank: QuestionBank) {
  if (!bank.wrong_questions_count) return
  await start(bank, 'wrong_practice')
}

async function openHistory(bank: QuestionBank) {
  historyBank.value = bank
  historyAttempts.value = []
  historyPage.value = 1
  historyDialogVisible.value = true
  await loadHistory()
}

async function loadHistory() {
  if (!historyBank.value) return
  historyLoading.value = true
  try {
    const response = await fetchBankAttemptHistory(historyBank.value.id, {
      page: historyPage.value,
      per_page: historyPageSize.value,
    })
    historyAttempts.value = response.data.items
    historyMeta.value = response.data.meta
  } finally {
    historyLoading.value = false
  }
}

async function changeHistoryPage(page: number) {
  historyPage.value = page
  await loadHistory()
}

async function changeHistoryPageSize(size: number) {
  historyPageSize.value = size
  historyPage.value = 1
  await loadHistory()
}

async function reviewAttempt(attempt: QuizAttemptHistory) {
  if (attempt.status !== 'submitted') {
    ElMessage.warning('只能回顾已提交的记录')
    return
  }
  await router.push(`/quiz/${attempt.id}`)
}

function formatDateTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value

  const pad = (number: number) => String(number).padStart(2, '0')

  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

async function startPaper(paper: Paper) {
  const response = await startPaperAttempt(paper.id)
  await router.push(`/quiz/${response.data.id}`)
}

onMounted(loadResources)
</script>

<template>
  <main class="resource-page">
    <section class="resource-head">
      <h1>学习入口</h1>
      <p>每个题库内完成背题、刷题和错题复盘。</p>
    </section>
    <section v-loading="loading" class="resource-section">
      <div class="resource-grid">
        <article v-for="bank in banks" :key="bank.id" class="resource-card">
          <div class="card-main">
            <h3>{{ bank.name }}</h3>
            <p>{{ bank.description || '暂无说明' }}</p>
            <div class="meta-line">
              <ElTag size="small" effect="plain">{{ bank.questions_count || 0 }} 题</ElTag>
              <ElTag size="small" type="warning" effect="plain">{{ bank.wrong_questions_count || 0 }} 错题</ElTag>
            </div>
          </div>
          <div class="resource-actions">
            <ElButton @click="start(bank, 'memorize')">顺序背题</ElButton>
            <ElButton type="primary" @click="start(bank, 'sequence')">顺序刷题</ElButton>
            <ElButton plain @click="openRandom(bank)">随机刷题</ElButton>
            <ElButton plain type="warning" :disabled="!bank.wrong_questions_count" @click="router.push(`/quiz/wrong-questions?bank_id=${bank.id}`)">错题列表</ElButton>
            <ElButton plain @click="openHistory(bank)">历史回顾</ElButton>
            <ElButton plain type="warning" :disabled="!bank.wrong_questions_count" @click="reviewWrong(bank)">重刷错题</ElButton>
          </div>
        </article>
      </div>
      <ElEmpty v-if="!loading && banks.length === 0" description="暂无可学习题库" />
    </section>

    <section v-loading="loading" class="resource-section">
      <div class="section-title">
        <h2>固定试卷</h2>
      </div>
      <div class="resource-grid">
        <article v-for="paper in papers" :key="paper.id" class="resource-card">
          <div>
            <h3>{{ paper.title }}</h3>
            <p>{{ paper.description || '暂无说明' }}</p>
          </div>
          <div class="meta-line">
            <ElTag size="small" effect="plain">{{ paper.questions_count || 0 }} 题</ElTag>
            <ElTag v-if="paper.duration_minutes" size="small" type="warning" effect="plain">
              {{ paper.duration_minutes }} 分钟
            </ElTag>
            <ElTag v-if="paper.attempt_limit" size="small" type="info" effect="plain">
              限 {{ paper.attempt_limit }} 次
            </ElTag>
          </div>
          <div class="resource-actions">
            <ElButton type="primary" @click="startPaper(paper)">开始测试</ElButton>
          </div>
        </article>
      </div>
      <ElEmpty v-if="!loading && papers.length === 0" description="暂无可用试卷" />
    </section>
  </main>

  <ElDialog v-model="randomDialogVisible" :title="randomTitle" width="min(520px, calc(100vw - 24px))" class="random-dialog">
    <ElForm :model="randomForm" label-position="top">
      <ElFormItem label="题目数量">
        <ElInputNumber v-model="randomForm.limit" :min="1" :max="100" class="w-full" />
      </ElFormItem>
      <ElFormItem label="题型">
        <ElCheckboxGroup v-model="randomForm.types">
          <ElCheckbox v-for="item in typeOptions" :key="item.value" :value="item.value">{{ item.label }}</ElCheckbox>
        </ElCheckboxGroup>
      </ElFormItem>
      <ElFormItem label="标签">
        <ElSelect v-model="randomForm.tag_ids" class="w-full" multiple clearable placeholder="不限标签">
          <ElOption v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="randomDialogVisible = false">取消</ElButton>
      <ElButton type="primary" @click="submitRandom">开始</ElButton>
    </template>
  </ElDialog>

  <ElDialog v-model="historyDialogVisible" :title="historyTitle" width="min(560px, calc(100vw - 24px))">
    <div v-loading="historyLoading" class="history-list">
      <ElEmpty v-if="!historyLoading && historyAttempts.length === 0" description="暂无已提交的刷题记录" />
      <article v-for="attempt in historyAttempts" :key="attempt.id" class="history-item">
        <div>
          <strong>{{ attempt.mode === 'random' ? '随机刷题' : '顺序刷题' }}</strong>
          <p>{{ formatDateTime(attempt.submitted_at || attempt.started_at) }}</p>
        </div>
        <div class="history-meta">
          <ElTag effect="plain">{{ attempt.correct_count }} / {{ attempt.total_questions }}</ElTag>
          <ElButton type="primary" plain @click="reviewAttempt(attempt)">回顾</ElButton>
        </div>
      </article>
      <ElPagination
        v-if="historyMeta.total > 0"
        class="history-pagination"
        layout="total, sizes, prev, pager, next"
        :total="historyMeta.total"
        :page-size="historyPageSize"
        :current-page="historyPage"
        :page-sizes="[10, 20, 50]"
        @update:current-page="changeHistoryPage"
        @update:page-size="changeHistoryPageSize"
      />
    </div>
  </ElDialog>
</template>

<style scoped>
.resource-page {
  width: min(1080px, 100%);
  margin: 0 auto;
  padding: 24px 16px 80px;
}

.resource-head {
  position: relative;
  margin-bottom: 18px;
}

.resource-head h1 {
  margin: 0 0 6px;
  font-size: 28px;
}

.resource-head p {
  margin: 0;
  color: var(--qq-muted);
}

.resource-section {
  margin-top: 22px;
  min-height: 170px;
}

.section-title {
  margin-bottom: 10px;
}

.section-title h2 {
  margin: 0;
  font-size: 18px;
}

.resource-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
  gap: 16px;
}

.resource-card {
  min-height: 176px;
  display: grid;
  grid-template-columns: minmax(0, 1fr) 260px;
  gap: 18px;
  align-items: center;
  padding: 22px;
  border: 1px solid var(--qq-line);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.72);
  backdrop-filter: blur(6px);
}

.resource-card h3 {
  margin: 0 0 8px;
  font-size: 18px;
}

.resource-card p {
  margin: 0;
  color: var(--qq-muted);
}

.card-main {
  min-width: 0;
}

.meta-line {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 12px;
}

.resource-actions {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px;
}

.history-list {
  min-height: 120px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 14px;
  padding: 12px 0;
  border-bottom: 1px solid var(--qq-line);
}

.history-item p {
  margin: 4px 0 0;
  color: var(--qq-muted);
  font-size: 13px;
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.history-pagination {
  margin-top: 14px;
  justify-content: flex-end;
}

.resource-actions :deep(.el-button) {
  width: 100%;
  justify-content: center;
  margin-left: 0;
}

@media (max-width: 640px) {
  .resource-grid {
    grid-template-columns: 1fr;
  }

  .resource-card {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .resource-actions {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .history-item {
    align-items: stretch;
    flex-direction: column;
  }

  .history-meta {
    justify-content: space-between;
  }

  .history-pagination {
    justify-content: flex-start;
    overflow-x: auto;
    padding-bottom: 4px;
  }

  :global(.random-dialog) {
    margin-top: 8vh;
  }

  :global(.random-dialog .el-dialog__body) {
    padding: 14px 16px;
  }

  :global(.random-dialog .el-dialog__footer) {
    padding: 12px 16px 16px;
  }
}
</style>
