<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import type {
  Category,
  CategoryTree,
  CreateCategoryRequest,
  UpdateCategoryRequest,
} from '@/types'
import { categoriesApi } from '@/api/categories'

const loading = ref(false)
const tree = ref<CategoryTree[]>([])

async function fetchTree() {
  loading.value = true
  try {
    tree.value = await categoriesApi.getCategoryTree()
  } finally {
    loading.value = false
  }
}

// ---------- Cascader ----------
interface CascaderNode {
  value: string
  label: string
  children?: CascaderNode[]
}

const cascaderOptions = ref<CascaderNode[]>([])

function buildCascader(nodes: CategoryTree[]): CascaderNode[] {
  return nodes.map((n) => ({
    value: n.id,
    label: n.categoryName,
    children: n.children?.length ? buildCascader(n.children) : undefined,
  }))
}

function rebuildCascader() {
  cascaderOptions.value = buildCascader(tree.value)
}

// ---------- Dialog ----------
const dialogRef = ref()
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const dialogLoading = ref(false)

const dialogForm = reactive<CreateCategoryRequest & { id?: string }>({
  categoryName: '',
  categoryIcon: '',
  parentCategoryId: '',
})

const dialogRules = {
  categoryName: [{ required: true, message: '名称是必填项', trigger: 'blur' }],
}

async function openAddDialog() {
  dialogMode.value = 'create'
  Object.assign(dialogForm, { id: undefined, categoryName: '', categoryIcon: '', parentCategoryId: '' })
  rebuildCascader()
  dialogVisible.value = true
}

async function openEditDialog(c: Category) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, {
    id: c.id,
    categoryName: c.categoryName,
    categoryIcon: c.categoryIcon || '',
    parentCategoryId: c.parentCategoryId || '',
  })
  rebuildCascader()
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!dialogRef.value) return
  await dialogRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    dialogLoading.value = true
    try {
      const payload: CreateCategoryRequest = {
        categoryName: dialogForm.categoryName,
        categoryIcon: dialogForm.categoryIcon || undefined,
        parentCategoryId: dialogForm.parentCategoryId || undefined,
      }
      if (dialogMode.value === 'create') {
        await categoriesApi.createCategory(payload)
        ElMessage.success('分类创建成功')
      } else {
        await categoriesApi.updateCategory(dialogForm.id!, payload as UpdateCategoryRequest)
        ElMessage.success('分类更新成功')
      }
      dialogVisible.value = false
      fetchTree()
    } finally {
      dialogLoading.value = false
    }
  })
}

async function handleDelete(c: Category) {
  try {
    await ElMessageBox.confirm(`确定删除「${c.categoryName}」吗？`, '确认', {
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
    })
  } catch {
    return
  }
  await categoriesApi.deleteCategory(c.id)
  ElMessage.success('删除成功')
  fetchTree()
}

onMounted(fetchTree)
</script>

<template>
  <div class="page-container">
    <div class="page-card">
      <div class="toolbar">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          <span>新增分类</span>
        </el-button>
        <el-button @click="fetchTree">
          <el-icon><Refresh /></el-icon>
          <span>刷新</span>
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tree"
        border
        row-key="id"
        :tree-props="{ children: 'children' }"
        default-expand-all
      >
        <el-table-column prop="categoryName" label="名称" min-width="220" />
        <el-table-column label="图标" width="100">
          <template #default="{ row }: { row: CategoryTree }">
            <el-image
              v-if="row.categoryIcon"
              :src="row.categoryIcon"
              :preview-src-list="[row.categoryIcon]"
              fit="cover"
              style="width: 32px; height: 32px; border-radius: 4px;"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="父级">
          <template #default="{ row }: { row: CategoryTree }">
            {{ row.parent?.categoryName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="子级数" width="100">
          <template #default="{ row }: { row: CategoryTree }">
            {{ row._count?.children ?? row.children?.length ?? 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }: { row: CategoryTree }">
            <div class="table-actions">
              <el-button size="small" type="primary" plain @click="openEditDialog(row)">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button size="small" type="danger" plain @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无分类" />
        </template>
      </el-table>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'create' ? '新增分类' : '编辑分类'"
      width="520px"
      destroy-on-close
    >
      <el-form
        ref="dialogRef"
        :model="dialogForm"
        :rules="dialogRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="categoryName">
          <el-input v-model="dialogForm.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="dialogForm.parentCategoryId"
            :options="cascaderOptions"
            :props="{
              checkStrictly: true,
              value: 'value',
              label: 'label',
              children: 'children',
              emitPath: false,
            }"
            placeholder="顶级（可选）"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="图标 URL">
          <el-input v-model="dialogForm.categoryIcon" placeholder="https://..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="dialogLoading" @click="handleSubmit">
          {{ dialogMode === 'create' ? '创建' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
