<script setup lang="ts">
import type { FormInst, UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui'
import {
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NCard,
  NDrawer,
  NDrawerContent,
  NEmpty,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NPagination,
  NRadio,
  NRadioGroup,
  NSelect,
  NTag,
  NUpload,
  useDialog,
  useMessage,
} from 'naive-ui'
import { computed, ref, watch } from 'vue'
import SvgIcon from '@/components/custom/svg-icon.vue'
import { questionTypeOptions } from '@/constants/business'
import { fetchAddQuestionLibrary, fetchDeleteQuestionLibrary, fetchGetQuestionLibraryListAll, fetchUpdateQuestionLibrary } from '@/service/api/question'

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

const message = useMessage()
const dialog = useDialog()

// 题目列表数据
const questionList = ref<any[]>([])
const loading = ref(false)

const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  onChange: (page: number) => {
    pagination.value.page = page
    if (props.currentCategory?.Id) {
      fetchData(props.currentCategory.Id)
    }
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    if (props.currentCategory?.Id) {
      fetchData(props.currentCategory.Id)
    }
  },
})

const searchText = ref('')
const showQuestionModal = ref(false)
const questionOperation = ref<'add' | 'edit'>('add')
const currentQuestionId = ref<number | null>(null)
const questionForm = ref({
  name: '',
  answer: '',
  type: 0,
  imageUrl: '',
  IsGood: 0,
})

const fileList = ref<UploadFileInfo[]>([])

const questionFormRef = ref<FormInst | null>(null)

const rules = {
  name: [{ required: true, message: '请输入题目正文内容', trigger: ['blur'] }],
  answer: [{ required: true, message: '请输入题目答案', trigger: ['blur'] }],
  type: [{ required: true, message: '请选择题目类型', trigger: ['change'], type: 'number' as const }],
}

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

watch(() => props.currentCategory, (newVal) => {
  if (newVal && newVal.Id) {
    pagination.value.page = 1
    searchText.value = ''
    fetchData(newVal.Id)
  }
  else {
    questionList.value = []
  }
}, { immediate: true })

function customRequest({ onFinish }: UploadCustomRequestOptions) {
  onFinish()
}

function handleUploadChange(data: { fileList: UploadFileInfo[] }) {
  fileList.value = data.fileList
}

async function fetchData(id: number) {
  loading.value = true
  const { data, error } = await fetchGetQuestionLibraryListAll({
    questionId: id,
    pageIndex: pagination.value.page,
    pageSizes: pagination.value.pageSize,
    keyWords: searchText.value,
  })
  // eslint-disable-next-line no-console
  console.log(data, 'data')
  if (!error) {
    questionList.value = data?.data?.QuestionListDetailList || []
    pagination.value.itemCount = data?.data?.TotalNum || 0
  }
  loading.value = false
}

function handleSearch() {
  pagination.value.page = 1
  if (props.currentCategory?.Id) {
    fetchData(props.currentCategory.Id)
  }
}

function handleAddQuestion() {
  if (!props.currentCategory) {
    message.warning('请先选择一个分类')
    return
  }
  questionOperation.value = 'add'
  currentQuestionId.value = null
  questionForm.value = { name: '', answer: '', type: 0, imageUrl: '', IsGood: 0 }
  fileList.value = []
  showQuestionModal.value = true
}

function handleEditQuestion(id: number) {
  const question = questionList.value.find(q => q.Id === id)
  if (question) {
    questionOperation.value = 'edit'
    currentQuestionId.value = id
    questionForm.value = {
      name: question.Name,
      answer: question.Answer,
      type: question.Type,
      imageUrl: question.ImageUrl || '',
      IsGood: question.IsPriority || 0,
    }
    fileList.value = []
    if (question.ImageUrl) {
      fileList.value = [{
        id: 'existing',
        name: 'Existing Image',
        status: 'finished',
        url: question.ImageUrl,
      }]
    }
    showQuestionModal.value = true
  }
}

function handleDeleteQuestion(id: number) {
  dialog.warning({
    title: '警告',
    content: '确定要删除这道题目吗？此操作无法撤销。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDeleteQuestionLibrary([id])
      if (!error) {
        message.success('删除成功')
        if (props.currentCategory?.Id) {
          fetchData(props.currentCategory.Id)
        }
      }
      else {
        message.error('删除失败')
      }
    },
  })
}

async function submitQuestion() {
  const valid = await questionFormRef.value?.validate()

  if (!valid) {
    message.error('请填写完整信息')
    return
  }

  const commonParams = {
    name: questionForm.value.name,
    answer: questionForm.value.answer,
    imageUrl: '',
    type: questionForm.value.type as any,
    questionId: props.currentCategory.Id,
    IsGood: questionForm.value.IsGood,
  }

  let fileToUpload: File | null = null
  if (questionForm.value.type === 1) { // 图片类型 (1: 图片, 0: 文字 - based on previous fixes)
    if (fileList.value.length > 0 && fileList.value[0].file) {
      fileToUpload = fileList.value[0].file
    }
    else if (questionOperation.value === 'add' && fileList.value.length === 0) {
      message.error('请上传图片')
      return
    }
    else if (questionOperation.value === 'edit' && fileList.value.length === 0) {
      message.error('请上传图片')
      return
    }
  }

  if (questionOperation.value === 'add') {
    const { error } = await fetchAddQuestionLibrary({
      ...commonParams,
      id: 0,
    }, fileToUpload)
    if (!error) {
      message.success('题目添加成功')
      showQuestionModal.value = false
      fetchData(props.currentCategory.Id)
    }
    else {
      message.error('添加失败')
    }
  }
  else if (questionOperation.value === 'edit' && currentQuestionId.value) {
    const { error } = await fetchUpdateQuestionLibrary({
      ...commonParams,
      id: currentQuestionId.value,
    }, fileToUpload)
    if (!error) {
      message.success('题目修改成功')
      showQuestionModal.value = false
      fetchData(props.currentCategory.Id)
    }
    else {
      message.error('修改失败')
    }
  }
}
</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.name }}
        </NBreadcrumbItem>
      </NBreadcrumb>

      <div class="flex items-center justify-between">
        <h1 class="m-0 text-xl text-gray-800 font-bold">
          {{ currentCategory ? currentCategory.name : '' }}
        </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" @keyup.enter="handleSearch">
            <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="!hasCategory">
        <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="questionList.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 questionList" :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>
                <NTag size="small" :type="q.IsGood === 1 ? 'info' : 'default'" :bordered="false">
                  {{ q.IsGood === 1 ? '优先' : '随机' }}
                </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.Name }}
            </div>

            <!-- 图片展示 -->
            <div v-if="q.ImageUrl" class="mb-2">
              <NImage :src="q.ImageUrl" width="100" class="block rounded-lg" />
            </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>
        <div class="mt-4 flex justify-end">
          <NPagination
            v-model:page="pagination.page" v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount" :page-sizes="pagination.pageSizes" show-size-picker
            @update:page="pagination.onChange" @update:page-size="pagination.onUpdatePageSize"
          >
            <template #prefix="{ itemCount }">
              共 {{ itemCount }} 项
            </template>
          </NPagination>
        </div>
      </template>
    </div>

    <!-- Add Question Drawer -->
    <NDrawer v-model:show="showQuestionModal" :width="800">
      <NDrawerContent :title="questionOperation === 'edit' ? '编辑题目详情' : '新增题目详情'">
        <NForm ref="questionFormRef" label-placement="top" :rules="rules" :model="questionForm" size="small">
          <NFormItem label="题目正文内容" path="name">
            <div class="w-full overflow-hidden border border-gray-200 rounded-lg">
              <!-- <RestBasicEditor v-model="questionForm.name" /> -->
              <NInput v-model:value="questionForm.name" 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="类型" path="type">
            <NSelect v-model:value="questionForm.type" class="w-full" :options="questionTypeOptions" />
          </NFormItem>

          <!-- 是否优先使用 -->
          <NFormItem label="是否优先使用" path="IsGood">
            <NRadioGroup v-model:value="questionForm.IsGood">
              <NRadio :value="0">
                否
              </NRadio>
              <NRadio :value="1">
                是
              </NRadio>
            </NRadioGroup>
          </NFormItem>

          <!-- 上传图片 -->
          <NFormItem v-if="questionForm.type === 1" label="上传图片">
            <NUpload
              v-model:file-list="fileList" accept="image/*" :max="1" list-type="image-card"
              :custom-request="customRequest" @change="handleUploadChange"
            >
              点击上传
            </NUpload>
          </NFormItem>

          <NFormItem label="参考标准答案" path="answer">
            <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>
