<script setup lang="ts">
import { computed, onMounted, reactive, shallowRef } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { createPaper, deletePaper, fetchBanks, fetchPaper, fetchPapers, fetchQuestions, updatePaper } from '@/api/admin'
import type { Paper, Question, QuestionBank } from '@/types/api'

const loading = shallowRef(false)
const detailLoading = shallowRef(false)
const dialogVisible = shallowRef(false)
const papers = shallowRef<Paper[]>([])
const banks = shallowRef<QuestionBank[]>([])
const questions = shallowRef<Question[]>([])
const selectedQuestionIds = shallowRef<number[]>([])
const form = reactive({
  id: 0,
  title: '',
  description: '',
  question_bank_id: undefined as number | undefined,
  duration_minutes: undefined as number | undefined,
  attempt_limit: undefined as number | undefined,
  is_active: true,
  score: 1,
})
const dialogTitle = computed(() => (form.id ? '编辑固定试卷' : '新建固定试卷'))
const availableQuestions = computed(() => {
  if (!form.question_bank_id) return questions.value
  return questions.value.filter((item) => item.question_bank_id === form.question_bank_id)
})

async function loadPapers() {
  loading.value = true
  try {
    const response = await fetchPapers()
    papers.value = response.data.items
  } finally {
    loading.value = false
  }
}

async function loadOptions() {
  const [bankResponse, questionResponse] = await Promise.all([
    fetchBanks({ per_page: 100 }),
    fetchQuestions({ per_page: 100 }),
  ])
  banks.value = bankResponse.data.items
  questions.value = questionResponse.data.items
}

function resetForm() {
  form.id = 0
  form.title = ''
  form.description = ''
  form.question_bank_id = undefined
  form.duration_minutes = undefined
  form.attempt_limit = undefined
  form.is_active = true
  form.score = 1
  selectedQuestionIds.value = []
}

function openCreate() {
  resetForm()
  dialogVisible.value = true
}

async function openEdit(row: Paper) {
  detailLoading.value = true
  try {
    const detail = (await fetchPaper(row.id)).data
    form.id = detail.id
    form.title = detail.title
    form.description = detail.description ?? ''
    form.question_bank_id = detail.question_bank_id
    form.duration_minutes = detail.duration_minutes
    form.attempt_limit = detail.attempt_limit
    form.is_active = detail.is_active
    const selectedQuestions = detail.questions ?? []
    selectedQuestionIds.value = selectedQuestions.map((item) => item.id)
    const firstScore = selectedQuestions.find((item) => item.pivot?.score !== undefined)?.pivot?.score
    form.score = firstScore === undefined ? 1 : Number(firstScore)
    dialogVisible.value = true
  } finally {
    detailLoading.value = false
  }
}

async function submitPaper() {
  const payload = {
    title: form.title,
    description: form.description,
    question_bank_id: form.question_bank_id,
    duration_minutes: form.duration_minutes,
    attempt_limit: form.attempt_limit,
    is_active: form.is_active,
    questions: selectedQuestionIds.value.map((id) => ({ id, score: form.score })),
  }
  if (form.id) {
    await updatePaper(form.id, payload)
    ElMessage.success('试卷已更新')
  } else {
    await createPaper(payload)
    ElMessage.success('试卷已创建')
  }
  dialogVisible.value = false
  resetForm()
  await loadPapers()
}

async function toggleActive(row: Paper) {
  await updatePaper(row.id, { is_active: !row.is_active })
  ElMessage.success(row.is_active ? '试卷已停用' : '试卷已启用')
  await loadPapers()
}

async function handleDelete(row: Paper) {
  await ElMessageBox.confirm(`确认删除试卷「${row.title}」？`, '删除试卷', { type: 'warning' })
  await deletePaper(row.id)
  ElMessage.success('试卷已删除')
  await loadPapers()
}

onMounted(() => {
  void loadPapers()
  void loadOptions()
})
</script>

<template>
  <section class="panel p-5">
    <div class="toolbar mb-4">
      <div class="flex-1">
        <h1 class="page-title">试卷管理</h1>
        <p class="muted text-sm mt-1">创建固定试卷，设置限时、次数和单题分值。</p>
      </div>
      <ElButton :icon="Plus" type="primary" @click="openCreate">新建试卷</ElButton>
    </div>

    <ElTable v-loading="loading" :data="papers" row-key="id">
      <ElTableColumn prop="title" label="试卷名称" min-width="180" />
      <ElTableColumn prop="questions_count" label="题量" width="90" />
      <ElTableColumn prop="duration_minutes" label="限时" width="110">
        <template #default="{ row }">{{ row.duration_minutes ? `${row.duration_minutes} 分钟` : '不限时' }}</template>
      </ElTableColumn>
      <ElTableColumn prop="attempt_limit" label="次数限制" width="110">
        <template #default="{ row }">{{ row.attempt_limit ?? '不限' }}</template>
      </ElTableColumn>
      <ElTableColumn prop="is_active" label="状态" width="100">
        <template #default="{ row }">
          <ElTag :type="row.is_active ? 'success' : 'info'">{{ row.is_active ? '启用' : '停用' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="description" label="说明" min-width="220" show-overflow-tooltip />
      <ElTableColumn label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <ElButton :icon="Edit" :loading="detailLoading" size="small" @click="openEdit(row)">编辑</ElButton>
          <ElButton size="small" @click="toggleActive(row)">{{ row.is_active ? '停用' : '启用' }}</ElButton>
          <ElButton :icon="Delete" size="small" type="danger" plain @click="handleDelete(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>
  </section>

  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="720px">
    <ElForm :model="form" label-position="top">
      <div class="grid gap-3 md:grid-cols-2">
        <ElFormItem label="名称">
          <ElInput v-model="form.title" />
        </ElFormItem>
        <ElFormItem label="题库">
          <ElSelect v-model="form.question_bank_id" class="w-full" clearable filterable>
            <ElOption v-for="item in banks" :key="item.id" :label="item.name" :value="item.id" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="限时分钟">
          <ElInputNumber v-model="form.duration_minutes" class="w-full" :min="1" controls-position="right" />
        </ElFormItem>
        <ElFormItem label="次数限制">
          <ElInputNumber v-model="form.attempt_limit" class="w-full" :min="1" controls-position="right" />
        </ElFormItem>
        <ElFormItem label="统一分值">
          <ElInputNumber v-model="form.score" class="w-full" :min="0" :step="0.5" controls-position="right" />
        </ElFormItem>
        <ElFormItem label="状态">
          <ElSwitch v-model="form.is_active" active-text="启用" inactive-text="停用" />
        </ElFormItem>
      </div>
      <ElFormItem label="说明">
        <ElInput v-model="form.description" type="textarea" />
      </ElFormItem>
      <ElFormItem label="题目">
        <ElSelect v-model="selectedQuestionIds" class="w-full" multiple filterable collapse-tags collapse-tags-tooltip>
          <ElOption
            v-for="item in availableQuestions"
            :key="item.id"
            :label="item.content"
            :value="item.id"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="dialogVisible = false">取消</ElButton>
      <ElButton type="primary" @click="submitPaper">保存</ElButton>
    </template>
  </ElDialog>
</template>
