<script setup lang="ts">
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  type SelectOption,
  useDialog,
  useMessage,
} from 'naive-ui'
import { onMounted, ref, watch } from 'vue'
import SvgIcon from '@/components/custom/svg-icon.vue'
import { QuestionType } from '@/enum/business'
import { useDict } from '@/hooks/business/useDict'
import { fetchAddQuestion, fetchDeleteQuestion, fetchGetQuestionListAll, fetchUpdateQuestion } from '@/service/api/question'

const emit = defineEmits<{
  (e: 'update:category', node: any): void
  (e: 'dragStart', event: MouseEvent): void
}>()

const { options: categoryOptions } = useDict('question_category_name', 'string')

const LOCAL_STORAGE_KEY = 'question-store-selected-category-id'

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

interface CategoryItem {
  Id: number
  Name: string
  QuestionContent: string
  QuestionType: QuestionType
}

// Mock Data - 模拟分类列表数据
const categoryList = ref<CategoryItem[]>([])

const selectedKey = ref<number | null>(null)

const showCategoryModal = ref(false)
const categoryForm = ref({ questionContent: '', name: '', Id: 0, questionType: QuestionType.Text })
const categoryOperation = ref<'add' | 'edit'>('add')
const currentOperationNode = ref<CategoryItem | null>(null)

watch(selectedKey, (newKey) => {
  if (!newKey) {
    emit('update:category', null)
    localStorage.removeItem(LOCAL_STORAGE_KEY)
    return
  }
  const node = categoryList.value.find(item => item.Id === newKey)
  if (node) {
    emit('update:category', {
      ...node,
    })
    localStorage.setItem(LOCAL_STORAGE_KEY, newKey.toString())
  }
  else {
    emit('update:category', null)
    localStorage.removeItem(LOCAL_STORAGE_KEY)
  }
})

function handleSelect(key: number) {
  selectedKey.value = key
}

/**
 * 分类名称选择更新
 * @param _value
 * @param option
 */
function handleCategoryNameChange(_value: string, option: SelectOption) {
  if (option)
    categoryForm.value.questionType = option.value as QuestionType
}

function handleAddCategory() {
  categoryOperation.value = 'add'
  categoryForm.value.questionContent = ''
  categoryForm.value.name = ''
  categoryForm.value.questionType = QuestionType.Text
  currentOperationNode.value = null
  showCategoryModal.value = true
}

function handleEditCategory(item: CategoryItem) {
  categoryOperation.value = 'edit'
  categoryForm.value.name = item.Name
  categoryForm.value.questionContent = item.QuestionContent
  categoryForm.value.questionType = item.QuestionType
  currentOperationNode.value = item
  showCategoryModal.value = true
}

function handleDeleteCategory(item: CategoryItem) {
  dialog.warning({
    title: '警告',
    content: `确定要删除分类 "${item.Name}" 吗？此操作无法撤销。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await fetchDeleteQuestion(item.Id)
      if (error) {
        message.error('删除分类失败')
        return
      }
      const index = categoryList.value.findIndex(n => n.Id === item.Id)
      if (index !== -1) {
        categoryList.value.splice(index, 1)
        if (selectedKey.value === item.Id) {
          selectedKey.value = null
        }
        // 获取最新分类列表
        await loadAndSelectCategory()
        message.success('删除成功')
      }
    },
  })
}

/**
 * 新增分类|更新分类
 * @param data 新增分类参数|更新分类参数
 */
async function submitCategory() {
  if (!categoryForm.value.name) {
    message.error('请输入分类名称')
    return
  }

  if (categoryOperation.value === 'add') {
    const { error } = await fetchAddQuestion({
      questionContent: categoryForm.value.questionContent,
      name: categoryForm.value.name,
      id: 0,
      questionType: categoryForm.value.questionType,
    })
    if (error) {
      message.error('添加分类失败')
      return
    }
    await loadAndSelectCategory()
    message.success('分类添加成功')
  }
  else if (categoryOperation.value === 'edit' && currentOperationNode.value) {
    const { error } = await fetchUpdateQuestion({
      questionContent: categoryForm.value.questionContent,
      name: categoryForm.value.name,
      id: currentOperationNode.value.Id,
      questionType: categoryForm.value.questionType,
    })
    if (error) {
      message.error('更新分类失败')
      return
    }
    currentOperationNode.value.QuestionContent = categoryForm.value.questionContent
    message.success('分类修改成功')
    await loadAndSelectCategory()
    // 更新选中分类的信息
    if (selectedKey.value === currentOperationNode.value.Id) {
      const node = currentOperationNode.value
      emit('update:category', {
        ...node,
        Name: categoryForm.value.name,
        QuestionContent: categoryForm.value.questionContent,
      })
    }
  }

  showCategoryModal.value = false
}

/**
 * 获取并选择分类列表
 */
async function loadAndSelectCategory() {
  try {
    const { data } = await fetchGetQuestionListAll()
    // Ensure Id is always a number to prevent type mismatch issues
    categoryList.value = (data?.data || []).map((c: any) => ({ ...c, Id: Number(c.Id) }))

    const savedKeyRaw = localStorage.getItem(LOCAL_STORAGE_KEY)
    const savedKey = savedKeyRaw ? Number(savedKeyRaw) : null
    const savedCategoryExists = savedKey ? categoryList.value.some(c => c.Id === savedKey) : false

    if (savedKey && savedCategoryExists) {
      selectedKey.value = savedKey
    }
    else if (categoryList.value.length > 0) {
      selectedKey.value = categoryList.value[0].Id
    }
    else {
      selectedKey.value = null
    }
  }
  catch (error: any) {
    message.error(error.message || '获取分类列表失败')
  }
}

onMounted(() => {
  loadAndSelectCategory()
})
</script>

<template>
  <div class="drag-handle relative h-full flex flex-col border-r border-gray-100 bg-gray-50/30">
    <div class="flex items-center justify-between border-b border-gray-100 px-4 py-4">
      <span class="text-lg text-gray-700 font-bold">题目分类</span>
      <NButton size="tiny" secondary type="primary" @click="handleAddCategory">
        <template #icon>
          <SvgIcon icon="ic:baseline-add" class="text-icon" />
        </template>
        新增
      </NButton>
    </div>

    <div class="flex-1 overflow-y-auto p-2">
      <div v-if="categoryList.length === 0" class="mt-10 text-center text-gray-400">
        暂无分类，请点击上方添加
      </div>
      <div
        v-for="item in categoryList" :key="item.Id"
        class="group mb-1 flex cursor-pointer items-center justify-between rounded-lg px-3 py-2.5 transition-all hover:bg-white hover:shadow-sm"
        :class="selectedKey === item.Id ? 'bg-white shadow-sm text-primary' : 'text-gray-600'"
        @click="handleSelect(item.Id)"
      >
        <div class="flex items-center gap-2 overflow-hidden">
          <SvgIcon
            icon="carbon:folder" class="flex-shrink-0 text-lg"
            :class="selectedKey === item.Id ? 'text-primary' : 'text-gray-400'"
          />
          <span class="truncate font-medium">{{ item.Name }} - {{ item.QuestionContent }}</span>
        </div>

        <!-- Action Buttons -->
        <div class="flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">
          <div
            class="flex cursor-pointer items-center p-1 text-gray-400 hover:text-blue-500" title="编辑"
            @click.stop="handleEditCategory(item)"
          >
            <SvgIcon icon="carbon:edit" class="text-base" />
          </div>
          <div
            class="flex cursor-pointer items-center p-1 text-gray-400 hover:text-red-500" title="删除"
            @click.stop="handleDeleteCategory(item)"
          >
            <SvgIcon icon="carbon:trash-can" class="text-base" />
          </div>
        </div>
      </div>
    </div>

    <div class="border-t border-gray-100 bg-gray-50 p-3 text-xs text-gray-400">
      提示：点击分类后，可在右侧管理该分类下的题目。
    </div>

    <!-- Add/Edit Category Modal -->
    <NModal
      v-model:show="showCategoryModal" preset="card" :title="categoryOperation === 'edit' ? '编辑分类' : '新增分类'"
      class="w-[500px]"
    >
      <NForm>
        <!-- 分类显示名称 -->
        <NFormItem label="分类名称">
          <NSelect
            v-model:value="categoryForm.name"
            :options="categoryOptions"
            value-field="label"
            placeholder="请选择分类名称"
            @update:value="handleCategoryNameChange"
          />
        </NFormItem>
        <!-- 题目类型 -->
        <NFormItem label="题目类型">
          <NInput v-model:value="categoryForm.questionType" placeholder="请选择分类名称自动带出" :readonly="true" />
        </NFormItem>
        <!-- 分类描述 -->
        <NFormItem label="分类描述">
          <NInput v-model:value="categoryForm.questionContent" placeholder="请输入分类描述" @keyup.enter="submitCategory" />
        </NFormItem>
      </NForm>
      <template #footer>
        <div class="flex justify-end gap-3">
          <NButton @click="showCategoryModal = false">
            取消
          </NButton>
          <NButton type="primary" @click="submitCategory">
            确认
          </NButton>
        </div>
      </template>
    </NModal>

    <!-- 拖动把手图标 -->
    <div
      class="absolute right-0 top-1/2 z-50 h-8 w-4 flex translate-x-1/2 cursor-col-resize items-center justify-center border border-gray-200 rounded-full bg-white shadow-sm transition-all -translate-y-1/2 hover:scale-110 hover:bg-gray-50"
      @mousedown="(e) => emit('dragStart', e)"
    >
      <SvgIcon icon="carbon:draggable" class="text-[10px] text-gray-400" />
    </div>
  </div>
</template>
