<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 { createQuestion, deleteQuestion, fetchBanks, fetchQuestions, updateQuestion } from '@/api/admin'
import type { Question, QuestionBank } from '@/types/api'

const loading = shallowRef(false)
const dialogVisible = shallowRef(false)
const questions = shallowRef<Question[]>([])
const banks = shallowRef<QuestionBank[]>([])
const total = shallowRef(0)
const filters = reactive({
  keyword: '',
  type: '',
  question_bank_id: '',
  is_active: '',
  page: 1,
  per_page: 20,
})
const form = reactive({
  id: 0,
  question_bank_id: undefined as number | undefined,
  type: 'single' as Question['type'],
  content: '',
  explanation: '',
  is_active: true,
  options: [
    { text: '', correct: true },
    { text: '', correct: false },
  ],
  answersText: '',
})

const dialogTitle = computed(() => (form.id ? '编辑题目' : '新增题目'))
const needsOptions = computed(() => form.type !== 'blank')
const typeLabels: Record<Question['type'], string> = {
  single: '单选',
  multiple: '多选',
  judge: '判断',
  blank: '填空',
}

async function loadQuestions() {
  loading.value = true
  try {
    const response = await fetchQuestions(filters)
    questions.value = response.data.items
    total.value = response.data.meta.total
  } finally {
    loading.value = false
  }
}

async function reloadQuestions() {
  filters.page = 1
  await loadQuestions()
}

async function loadBanks() {
  banks.value = (await fetchBanks({ per_page: 100 })).data.items
}

function resetForm() {
  form.id = 0
  form.question_bank_id = banks.value[0]?.id
  form.type = 'single'
  form.content = ''
  form.explanation = ''
  form.is_active = true
  form.options = [
    { text: '', correct: true },
    { text: '', correct: false },
  ]
  form.answersText = ''
}

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

function openEdit(row: Question) {
  form.id = row.id
  form.question_bank_id = row.question_bank_id
  form.type = row.type
  form.content = row.content
  form.explanation = row.explanation ?? ''
  form.is_active = row.is_active
  form.options = row.options?.map((option) => ({ text: option.content, correct: option.is_correct })) ?? [
    { text: '', correct: true },
    { text: '', correct: false },
  ]
  form.answersText = row.answers?.join('|') ?? ''
  dialogVisible.value = true
}

function addOption() {
  form.options.push({ text: '', correct: false })
}

function removeOption(index: number) {
  if (form.options.length > 2) {
    form.options.splice(index, 1)
  }
}

async function submitQuestion() {
  const payload = {
    question_bank_id: form.question_bank_id,
    type: form.type,
    content: form.content,
    explanation: form.explanation,
    is_active: form.is_active,
    options: needsOptions.value ? form.options : [],
    answers: form.type === 'blank' ? form.answersText.split('|').map((item) => item.trim()).filter(Boolean) : [],
  }
  if (form.id) {
    await updateQuestion(form.id, {
      type: payload.type,
      content: payload.content,
      explanation: payload.explanation,
      is_active: payload.is_active,
      options: payload.options as never,
      answers: payload.answers as never,
    })
    ElMessage.success('题目已更新')
  } else {
    await createQuestion(payload)
    ElMessage.success('题目已创建')
  }
  dialogVisible.value = false
  await loadQuestions()
}

async function toggleActive(row: Question) {
  await updateQuestion(row.id, { is_active: !row.is_active })
  ElMessage.success(row.is_active ? '题目已停用' : '题目已启用')
  await loadQuestions()
}

async function handleDelete(row: Question) {
  await ElMessageBox.confirm('确认删除该题目？', '删除题目', { type: 'warning' })
  await deleteQuestion(row.id)
  ElMessage.success('题目已删除')
  await loadQuestions()
}

onMounted(async () => {
  await loadBanks()
  await loadQuestions()
})
</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>
      <ElSelect v-model="filters.question_bank_id" class="max-w-48" placeholder="题库" clearable @change="reloadQuestions">
        <ElOption v-for="bank in banks" :key="bank.id" :label="bank.name" :value="bank.id" />
      </ElSelect>
      <ElInput v-model="filters.keyword" class="max-w-64" placeholder="搜索题干" clearable @change="reloadQuestions" />
      <ElSelect v-model="filters.type" class="max-w-40" placeholder="题型" clearable @change="reloadQuestions">
        <ElOption label="单选" value="single" />
        <ElOption label="多选" value="multiple" />
        <ElOption label="判断" value="judge" />
        <ElOption label="填空" value="blank" />
      </ElSelect>
      <ElSelect v-model="filters.is_active" class="max-w-32" placeholder="状态" clearable @change="reloadQuestions">
        <ElOption label="启用" value="1" />
        <ElOption label="停用" value="0" />
      </ElSelect>
      <ElButton :icon="Plus" type="primary" @click="openCreate">新增题目</ElButton>
    </div>

    <ElTable v-loading="loading" :data="questions" row-key="id">
      <ElTableColumn prop="content" label="题干" min-width="320" show-overflow-tooltip />
      <ElTableColumn prop="type" label="题型" width="100">
        <template #default="{ row }">
          {{ typeLabels[row.type as Question['type']] || row.type }}
        </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 label="操作" width="260" fixed="right">
        <template #default="{ row }">
          <ElButton :icon="Edit" 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>
    <div class="pagination-bar">
      <ElPagination
        v-model:current-page="filters.page"
        v-model:page-size="filters.per_page"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="reloadQuestions"
        @current-change="loadQuestions"
      />
    </div>
  </section>

  <ElDialog v-model="dialogVisible" :title="dialogTitle" width="640px">
    <ElForm :model="form" label-position="top">
      <ElFormItem v-if="!form.id" label="题库">
        <ElSelect v-model="form.question_bank_id" class="w-full" filterable>
          <ElOption v-for="bank in banks" :key="bank.id" :label="bank.name" :value="bank.id" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="题型">
        <ElSelect v-model="form.type" class="w-full">
          <ElOption label="单选" value="single" />
          <ElOption label="多选" value="multiple" />
          <ElOption label="判断" value="judge" />
          <ElOption label="填空" value="blank" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="题干">
        <ElInput v-model="form.content" type="textarea" :rows="4" />
      </ElFormItem>
      <ElFormItem label="解析">
        <ElInput v-model="form.explanation" type="textarea" :rows="3" />
      </ElFormItem>
      <ElFormItem v-if="needsOptions" label="选项">
        <div class="option-list">
          <div v-for="(option, index) in form.options" :key="index" class="option-row">
            <ElCheckbox v-model="option.correct">正确</ElCheckbox>
            <ElInput v-model="option.text" placeholder="选项内容" />
            <ElButton text type="danger" @click="removeOption(index)">删除</ElButton>
          </div>
          <ElButton @click="addOption">添加选项</ElButton>
        </div>
      </ElFormItem>
      <ElFormItem v-if="form.type === 'blank'" label="填空答案">
        <ElInput v-model="form.answersText" placeholder="多个答案用 | 分隔" />
      </ElFormItem>
      <ElFormItem label="状态">
        <ElSwitch v-model="form.is_active" active-text="启用" inactive-text="停用" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="dialogVisible = false">取消</ElButton>
      <ElButton type="primary" @click="submitQuestion">保存</ElButton>
    </template>
  </ElDialog>
</template>

<style scoped>
.option-list {
  width: 100%;
  display: grid;
  gap: 10px;
}

.option-row {
  display: grid;
  grid-template-columns: 72px minmax(0, 1fr) 56px;
  gap: 8px;
  align-items: center;
}

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

@media (max-width: 640px) {
  .option-row {
    grid-template-columns: 1fr;
  }
}
</style>
