<template>
  <NDropdown
    placement="bottom-start"
    trigger="manual"
    :x="x"
    :y="y"
    :options="options"
    :show="showDropdown"
    @clickoutside="onClickOutside"
    @select="handleSelect"
  />
</template>

<script setup lang="ts">
import { ref, h } from 'vue';
import { NDropdown, useDialog, useMessage, NInput } from 'naive-ui';
import { editBookCatalogAxios, type CatalogTree } from '@/service/api/book';
import IconSolarPen2Linear from '~icons/solar/pen-2-linear';

const showDropdown = ref(false);
const x = ref(0);
const y = ref(0);
const currentData = ref<CatalogTree | null>(null);

const dialog = useDialog();
const message = useMessage();
const emit = defineEmits(['rename', 'delete', 'add']);

const options = [
  {
    label: '重命名',
    key: 'rename',
    icon: () => h(IconSolarPen2Linear)
  },
];

type ShowData = {
  treeData: CatalogTree;
  event: MouseEvent;
  bookId: number;
  renameCallBack?: (name: string) => void;
};

let renameCallBack: ((name: string) => void) | undefined;

function show(data: ShowData) {
  data.event.preventDefault();
  showDropdown.value = false;
  currentData.value = data.treeData;
  renameCallBack = data.renameCallBack;
  
  setTimeout(() => {
    x.value = data.event.clientX;
    y.value = data.event.clientY;
    showDropdown.value = true;
  }, 10);
}

function onClickOutside() {
  showDropdown.value = false;
}

function handleSelect(key: string) {
  showDropdown.value = false;
  if (key === 'rename') {
    handleRename();
  }
}

function handleRename() {
  if (!currentData.value) return;
  
  let tempName = currentData.value.name;
  
  const d = dialog.create({
    title: '重命名',
    content: () => {
        return h(NInput, {
            defaultValue: tempName,
            placeholder: '请输入目录名称',
            onUpdateValue: (v) => tempName = v
        })
    },
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
        if (!tempName) {
            message.warning('请输入名称');
            return false;
        }
        try {
             d.loading = true;
             // Assuming API expects id and name. The original code had `editBookCatalogAxios`.
             // I'll call API here or use callback.
             // Original code logic was mixed. I'll use API here for simplicity if callback is just for UI update.
             
             // Check if we should call API or just callback
             await editBookCatalogAxios({
                 id: currentData.value!.id,
                 name: tempName,
                 type: currentData.value!.type,
                 bookId: currentData.value!.bookId // Assuming bookId is in data or passed
             });
             
             if (renameCallBack) {
                 renameCallBack(tempName);
             } else if (currentData.value) {
                 currentData.value.name = tempName;
             }
             message.success('修改成功');
             return true;
        } catch(e: any) {
             message.error(e.message || '修改失败');
             return false;
        } finally {
            d.loading = false;
        }
    }
  });
}

defineExpose({ show });
</script>
