<script setup lang="ts">
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NModal,
  useDialog,
  useMessage,
} from 'naive-ui'
import { ref, watch } from 'vue'
import SvgIcon from '@/components/custom/svg-icon.vue'

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

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

interface CategoryItem {
  key: string
  label: string
}

// Mock Data - 模拟分类列表数据
const categoryList = ref<CategoryItem[]>([
  {
    key: 'stage-1',
    label: '请根据提示书写正确的汉字。',
  },
  {
    key: 'stage-2',
    label: '请写出含有“车”的汉字。',
  },
  {
    key: 'poem',
    label: '请根据拼音书写正确的词语。',
  },
  {
    key: 'stage-extra-1',
    label: '请写出含有反义字的四字成语。',
  },
  {
    key: 'stage-extra-2',
    label: '请根据图片书写正确的成语。',
  },
])

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

// Modal State
const showCategoryModal = ref(false)
const categoryForm = ref({ name: '' })
const categoryOperation = ref<'add' | 'edit'>('add')
const currentOperationNode = ref<CategoryItem | null>(null)

watch(selectedKey, (newKey) => {
  if (!newKey) {
    emit('update:category', null)
    return
  }
  const node = categoryList.value.find(item => item.key === newKey)
  if (node) {
    emit('update:category', {
      ...node,
      level: 1, // Treat all as level 1
      isLeaf: true, // Treat all as leaf (container for questions)
    })
  }
  else {
    emit('update:category', null)
  }
})

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

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

function handleEditCategory(item: CategoryItem) {
  categoryOperation.value = 'edit'
  categoryForm.value.name = item.label
  currentOperationNode.value = item
  showCategoryModal.value = true
}

function handleDeleteCategory(item: CategoryItem) {
  dialog.warning({
    title: '警告',
    content: `确定要删除分类 "${item.label}" 吗？此操作无法撤销。`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = categoryList.value.findIndex(n => n.key === item.key)
      if (index !== -1) {
        categoryList.value.splice(index, 1)
        if (selectedKey.value === item.key) {
          selectedKey.value = null
        }
        message.success('删除成功')
      }
    },
  })
}

function submitCategory() {
  if (!categoryForm.value.name) {
    message.error('请输入分类名称')
    return
  }

  if (categoryOperation.value === 'add') {
    const newKey = `cate-${Date.now()}`
    categoryList.value.push({
      key: newKey,
      label: categoryForm.value.name,
    })
    message.success('分类添加成功')
    // Automatically select the new category
    selectedKey.value = newKey
  }
  else if (categoryOperation.value === 'edit' && currentOperationNode.value) {
    currentOperationNode.value.label = categoryForm.value.name
    message.success('分类修改成功')
    // Trigger update if currently selected
    if (selectedKey.value === currentOperationNode.value.key) {
      const node = currentOperationNode.value
      emit('update:category', {
        ...node,
        level: 1,
        isLeaf: true,
      })
    }
  }

  showCategoryModal.value = false
}
</script>

<template>
  <div class="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.key"
        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.key ? 'bg-white shadow-sm text-primary' : 'text-gray-600'"
        @click="handleSelect(item.key)"
      >
        <div class="flex items-center gap-2 overflow-hidden">
          <SvgIcon
            icon="carbon:folder" class="flex-shrink-0 text-lg"
            :class="selectedKey === item.key ? 'text-primary' : 'text-gray-400'"
          />
          <span class="truncate font-medium">{{ item.label }}</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="分类名称">
          <NInput v-model:value="categoryForm.name" 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>
</template>

<style scoped>
/* No specific styles needed as we use Tailwind classes */
</style>
