<script setup lang="ts">
import {
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NCard,
  NDrawer,
  NDrawerContent,
  NEmpty,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NTag,

} from 'naive-ui'
import { computed, ref } from 'vue'
import SvgIcon from '@/components/custom/svg-icon.vue'

const props = defineProps<{
  currentCategory: any
}>()

// Mock Data - 模拟题目列表数据
const questionList = ref([
  {
    id: 'Q-0325',
    categoryKey: 'stage-1',
    content: 'jiū 表示小鸟的叫声',
    answer: '碧',
    score: 10,
    time: 30,
  },
  {
    id: 'Q-0326',
    categoryKey: 'stage-1',
    content: '“春色满园关不住，一枝红杏出墙来”。请书写“杏”字。',
    answer: '杏',
    score: 10,
    time: 30,
  },
  {
    id: 'Q-0327',
    categoryKey: 'stage-1',
    content: '“春色满园关不住，一枝红杏出墙来”。请书写“㽱”字。',
    answer: '㽱',
    score: 10,
    time: 30,
  },
  {
    id: 'Q-0328',
    categoryKey: 'stage-1',
    content: '“春色满园关不住，一枝红杏出墙来”。请书写“不”字。',
    answer: '不',
    score: 10,
    time: 30,
  },
  {
    id: 'Q-0329',
    categoryKey: 'q-type-2',
    content: 'táng',
    answer: '糖',
    score: 10,
    time: 30,
  },
  {
    id: 'Q-0330',
    categoryKey: 'q-type-2',
    content: 'lái',
    answer: '莱',
    score: 10,
    time: 30,
  },
  {
    id: 'Q-0331',
    categoryKey: 'q-type-3',
    content: '请写出含有“木”字的汉字。',
    answer: '林',
    score: 10,
    time: 30,
  },
])

const searchText = ref('')
const showQuestionModal = ref(false)
const questionOperation = ref<'add' | 'edit'>('add')
const currentQuestionId = ref<string | null>(null)
const questionForm = ref({
  content: '',
  answer: '',
  score: 10,
  time: 30,
  imageUrl: '',
})

const isLeafSelected = computed(() => {
  return !!props.currentCategory
})

const filteredQuestions = computed(() => {
  let list = questionList.value

  // 1. Filter by Category Key
  if (props.currentCategory && props.currentCategory.key) {
    list = list.filter(q => q.categoryKey === props.currentCategory.key)
  }

  // 2. Filter by Search Text
  if (searchText.value) {
    list = list.filter(q => q.content.includes(searchText.value))
  }

  return list
})

function handleAddQuestion() {
  if (!props.currentCategory) {
    window.$message?.warning('请先选择一个分类')
    return
  }
  questionOperation.value = 'add'
  currentQuestionId.value = null
  questionForm.value = { content: '', answer: '', score: 10, time: 30, imageUrl: '' }
  showQuestionModal.value = true
}

function handleEditQuestion(id: string) {
  const question = questionList.value.find(q => q.id === id)
  if (question) {
    questionOperation.value = 'edit'
    currentQuestionId.value = id
    questionForm.value = {
      content: question.content,
      answer: question.answer,
      score: question.score,
      time: question.time,
      imageUrl: (question as any).imageUrl || '',
    }
    showQuestionModal.value = true
  }
}

function handleDeleteQuestion(id: string) {
  window.$dialog?.warning({
    title: '警告',
    content: '确定要删除这道题目吗？此操作无法撤销。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = questionList.value.findIndex(q => q.id === id)
      if (index !== -1) {
        questionList.value.splice(index, 1)
        window.$message?.success('删除成功')
      }
    },
  })
}

function submitQuestion() {
  if (!questionForm.value.content || !questionForm.value.answer) {
    window.$message?.error('请填写完整信息')
    return
  }
  // eslint-disable-next-line no-console
  console.log('questionForm.value', questionForm.value)

  if (questionOperation.value === 'add') {
    // Mock add
    questionList.value.push({
      id: `Q-${Math.floor(Math.random() * 10000)}`,
      ...questionForm.value,
      categoryKey: props.currentCategory?.key, // Add categoryKey
    })
    window.$message?.success('题目添加成功')
  }
  else if (questionOperation.value === 'edit' && currentQuestionId.value) {
    const index = questionList.value.findIndex(q => q.id === currentQuestionId.value)
    if (index !== -1) {
      questionList.value[index] = {
        ...questionList.value[index],
        ...questionForm.value,
      }
      window.$message?.success('题目修改成功')
    }
  }
  showQuestionModal.value = false
}
</script>

<template>
  <div class="h-full flex flex-col flex-1 overflow-hidden bg-white">
    <!-- 分类面包屑导航 -->
    <div class="flex flex-col gap-4 border-b border-gray-100 px-6 py-4">
      <NBreadcrumb>
        <NBreadcrumbItem>题库全集</NBreadcrumbItem>
        <NBreadcrumbItem v-if="currentCategory && currentCategory.level === 1">
          {{ currentCategory.label }}
        </NBreadcrumbItem>
      </NBreadcrumb>

      <div class="flex items-center justify-between">
        <h1 class="m-0 text-xl text-gray-800 font-bold">
          {{ currentCategory ? currentCategory.label : '' }}
        </h1>
      </div>

      <!-- 搜索框 -->
      <div v-if="currentCategory" class="mt-2 flex items-center justify-between">
        <div class="flex items-center gap-3">
          <NInput v-model:value="searchText" placeholder="输入题目关键字在当前分类下搜索..." class="!w-80">
            <template #prefix>
              <SvgIcon icon="carbon:search" class="text-gray-400" />
            </template>
          </NInput>
        </div>

        <NButton type="primary" @click="handleAddQuestion">
          <template #icon>
            <SvgIcon icon="carbon:add" />
          </template>
          新增题目
        </NButton>
      </div>
    </div>

    <!-- 题目列表区域 -->
    <div class="flex-1 overflow-y-auto bg-gray-50/50 p-6">
      <template v-if="!isLeafSelected">
        <div class="h-full flex flex-col items-center justify-center text-gray-400">
          <NEmpty description="暂无数据">
            <template #extra>
              请从左侧选择一个分类以管理题目数据
            </template>
          </NEmpty>
        </div>
      </template>

      <template v-else-if="filteredQuestions.length === 0">
        <div class="mt-20 flex justify-center">
          <NEmpty description="该分类下暂无题目" />
        </div>
      </template>

      <!-- 题目列表 -->
      <template v-else>
        <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
          <NCard v-for="q in filteredQuestions" :key="q.id" size="small" hoverable class="rounded-xl">
            <template #header>
              <div class="flex items-center gap-2">
                <NTag size="small" type="primary" :bordered="false">
                  ID: {{ q.id }}
                </NTag>
              </div>
            </template>
            <template #header-extra>
              <span class="text-xs text-gray-400 font-mono">{{ q.score }} PTS / {{ q.time }} S</span>
            </template>

            <div class="py-2 text-base text-gray-700 font-medium">
              {{ q.content }}
            </div>

            <!-- 标准答案 -->
            <div class="mt-3 border border-green-100 rounded-lg bg-green-50 p-3">
              <div class="mb-1 text-xs text-green-600 font-bold tracking-wider uppercase">
                STANDARD ANSWER
              </div>
              <div class="text-green-800 font-bold">
                {{ q.answer }}
              </div>
            </div>

            <!-- 操作按钮 -->
            <template #action>
              <div class="flex justify-end gap-2">
                <NButton size="tiny" quaternary type="primary" @click="handleEditQuestion(q.id)">
                  <template #icon>
                    <SvgIcon icon="carbon:edit" />
                  </template>
                </NButton>
                <NButton size="tiny" quaternary type="error" @click="handleDeleteQuestion(q.id)">
                  <template #icon>
                    <SvgIcon icon="carbon:trash-can" />
                  </template>
                </NButton>
              </div>
            </template>
          </NCard>
        </div>
      </template>
    </div>

    <!-- Add Question Drawer -->
    <NDrawer v-model:show="showQuestionModal" :width="800">
      <NDrawerContent :title="questionOperation === 'edit' ? '编辑题目详情' : '新增题目详情'">
        <NForm label-placement="top">
          <NFormItem label="题目正文内容">
            <div class="w-full overflow-hidden border border-gray-200 rounded-lg">
              <!-- <RestBasicEditor v-model="questionForm.content" /> -->
              <NInput v-model:value="questionForm.content" type="textarea" class="h-64 w-full" />
            </div>
          </NFormItem>

          <div class="grid grid-cols-2 gap-4">
            <NFormItem label="参考分值 (Pts)">
              <NInputNumber v-model:value="questionForm.score" class="w-full" :min="1" />
            </NFormItem>
            <NFormItem label="限时 (S)">
              <NInputNumber v-model:value="questionForm.time" class="w-full" :min="1" />
            </NFormItem>
          </div>

          <!-- 上传图片 -->
          <NFormItem label="上传图片">
            <RestUpload v-model="questionForm.imageUrl" width="100px" height="100px" hint="请上传题目图片" />
          </NFormItem>

          <NFormItem label="参考标准答案">
            <NInput v-model:value="questionForm.answer" placeholder="正确答案" />
          </NFormItem>
        </NForm>
        <template #footer>
          <div class="flex justify-end gap-3">
            <NButton @click="showQuestionModal = false">
              取消并返回
            </NButton>
            <NButton type="primary" @click="submitQuestion">
              保存并入库
            </NButton>
          </div>
        </template>
      </NDrawerContent>
    </NDrawer>
  </div>
</template>
