<script setup>
import { ref, computed, inject } from "vue";
import { q, m } from "#imports";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
const reloadMenu = inject("reloadMenu");
const { t } = useI18n();
const $q = useQuasar();
const { app, my } = await q({
  app: {
    menus: true
  },
  my: {
    menu: true
  }
});
const getUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
    let r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
    return v.toString(16);
  }).toUpperCase();
};
const convertMenusToTree = (menus) => {
  if (!menus) return [];
  return menus.map((menu) => ({
    ...menu,
    uuid: menu.uuid || getUUID(),
    icon: menu.icon || "sym_o_menu",
    children: menu.children ? convertMenusToTree(menu.children) : []
  }));
};
const availableMenus = ref(convertMenusToTree(app.menus));
const userMenus = ref([
  {
    label: "[My Menu]",
    uuid: "ROOT",
    children: my.menu,
    type: "root"
  }
]);
const selectedNode = ref("ROOT");
const splitterModel = ref(30);
const userMenuTree = ref(null);
const currentNodeDetail = computed(() => {
  if (selectedNode.value === "ROOT") return userMenus.value[0];
  if (!userMenuTree.value) return null;
  return userMenuTree.value.getNodeByKey(selectedNode.value);
});
const cloneMenuWithChildren = (menu, parentUuid) => {
  const clonedMenu = {
    ...menu,
    uuid: getUUID(),
    parent: parentUuid,
    children: []
  };
  if (menu.children && menu.children.length > 0) {
    clonedMenu.children = menu.children.map(
      (child) => cloneMenuWithChildren(child, clonedMenu.uuid)
    );
  }
  return clonedMenu;
};
const addMenuToCustom = (menu) => {
  const targetNode = currentNodeDetail.value;
  if (!targetNode) return;
  const newMenuItem = cloneMenuWithChildren(menu, targetNode.uuid);
  if (!targetNode.children) targetNode.children = [];
  targetNode.children.push(newMenuItem);
  if (userMenuTree.value && targetNode.uuid !== "ROOT") {
    userMenuTree.value.setExpanded(selectedNode.value, true);
  }
  if (newMenuItem.children && newMenuItem.children.length > 0) {
    setTimeout(() => {
      if (userMenuTree.value) {
        userMenuTree.value.setExpanded(newMenuItem.uuid, true);
      }
    }, 100);
  }
};
const createNewFolder = () => {
  $q.dialog({
    title: "Create New Folder",
    message: "Please enter folder name",
    prompt: {
      model: "",
      type: "text"
    },
    cancel: true,
    persistent: true
  }).onOk((folderName) => {
    if (folderName.trim() === "") return;
    const targetNode = currentNodeDetail.value;
    if (!targetNode) return;
    const newFolder = {
      label: folderName,
      uuid: getUUID(),
      parent: targetNode.uuid,
      children: [],
      icon: "sym_o_folder"
    };
    if (!targetNode.children) targetNode.children = [];
    targetNode.children.push(newFolder);
    if (userMenuTree.value && targetNode.uuid !== "ROOT") {
      userMenuTree.value.setExpanded(selectedNode.value, true);
    }
  });
};
const createNewSubItem = () => {
  $q.dialog({
    title: "Create New Sub Item",
    message: "Please enter item name",
    prompt: {
      model: "",
      type: "text"
    },
    cancel: true,
    persistent: true
  }).onOk((itemName) => {
    if (itemName.trim() === "") return;
    const targetNode = currentNodeDetail.value;
    if (!targetNode) return;
    const newItem = {
      label: itemName,
      uuid: getUUID(),
      parent: targetNode.uuid,
      children: [],
      icon: "sym_o_menu",
      to: ""
    };
    if (!targetNode.children) targetNode.children = [];
    targetNode.children.push(newItem);
    if (userMenuTree.value && targetNode.uuid !== "ROOT") {
      userMenuTree.value.setExpanded(selectedNode.value, true);
    }
    selectedNode.value = newItem.uuid;
  });
};
const addSeparator = () => {
  const targetNode = currentNodeDetail.value;
  if (!targetNode) return;
  const separator = {
    label: "[Separator]",
    uuid: getUUID(),
    parent: targetNode.uuid,
    children: [],
    type: "separator",
    spaced: true
  };
  if (!targetNode.children) targetNode.children = [];
  targetNode.children.push(separator);
};
const removeMenuItem = (node) => {
  if (node.type === "root") return;
  $q.dialog({
    title: "Confirm Delete",
    message: `Are you sure you want to delete "${node.label}"?`,
    cancel: true,
    persistent: true
  }).onOk(() => {
    const parent = getParentNode(node);
    if (parent && parent.children) {
      parent.children = parent.children.filter((item) => item.uuid !== node.uuid);
      selectedNode.value = parent.uuid;
    }
  });
};
const getParentNode = (node) => {
  if (!node.parent || node.parent === "ROOT") {
    return userMenus.value[0];
  }
  return userMenuTree.value.getNodeByKey(node.parent);
};
const moveUp = (node) => {
  const parent = getParentNode(node);
  if (!parent || !parent.children) return;
  const index = parent.children.findIndex((item) => item.uuid === node.uuid);
  if (index > 0) {
    const temp = parent.children[index - 1];
    parent.children[index - 1] = node;
    parent.children[index] = temp;
  }
};
const moveDown = (node) => {
  const parent = getParentNode(node);
  if (!parent || !parent.children) return;
  const index = parent.children.findIndex((item) => item.uuid === node.uuid);
  if (index < parent.children.length - 1) {
    const temp = parent.children[index + 1];
    parent.children[index + 1] = node;
    parent.children[index] = temp;
  }
};
const showMoveDialog = ref(false);
const moveTarget = ref(null);
const moveToGroup = () => {
  showMoveDialog.value = true;
  moveTarget.value = null;
};
const confirmMove = () => {
  if (!moveTarget.value || !currentNodeDetail.value) return;
  const nodeToMove = JSON.parse(JSON.stringify(currentNodeDetail.value));
  removeMenuItem(currentNodeDetail.value);
  nodeToMove.parent = moveTarget.value;
  const targetNode = moveTarget.value === "ROOT" ? userMenus.value[0] : userMenuTree.value.getNodeByKey(moveTarget.value);
  if (!targetNode.children) targetNode.children = [];
  targetNode.children.push(nodeToMove);
  if (userMenuTree.value && moveTarget.value !== "ROOT") {
    userMenuTree.value.setExpanded(moveTarget.value, true);
  }
  showMoveDialog.value = false;
  selectedNode.value = nodeToMove.uuid;
};
const saveCustomMenus = async () => {
  try {
    await m("updateMyMenu", {
      menu: userMenus.value[0].children
    });
    if (reloadMenu) {
      reloadMenu();
    }
  } catch (e) {
    console.error("Failed to save custom menu:", e);
    $q.notify({
      message: "Failed to save custom menu",
      color: "negative",
      icon: "error",
      position: "top",
      timeout: 2e3
    });
    return;
  }
  $q.notify({
    message: "Menu structure saved successfully",
    color: "positive",
    icon: "check",
    position: "top",
    timeout: 2e3
  });
};
const resetMenus = () => {
  $q.dialog({
    title: "Confirm Reset",
    message: "This will clear all custom menu settings. Are you sure you want to reset?",
    cancel: true,
    persistent: true
  }).onOk(() => {
    userMenus.value[0].children = [];
    selectedNode.value = "ROOT";
  });
};
</script>

<template>
    <div>
        <!-- Move to group dialog -->
        <q-dialog v-model="showMoveDialog">
            <l-card>
                <q-card-section>
                    <div class="text-h6">Select Move Target</div>
                    <q-tree :nodes="userMenus" default-expand-all v-model:selected="moveTarget" node-key="uuid" />
                </q-card-section>
                <q-card-actions align="right">
                    <q-btn flat label="Cancel" color="primary" v-close-popup />
                    <q-btn flat label="Move" color="primary" @click="confirmMove" />
                </q-card-actions>
            </l-card>
        </q-dialog>

        <l-card>
            <q-card-actions class="q-gutter-sm">
                <l-btn @click="saveCustomMenus" label="Save Custom Menu" icon="sym_o_save" />
                <l-btn @click="resetMenus" label="Reset Menu" icon="sym_o_refresh" />
            </q-card-actions>

            <q-splitter v-model="splitterModel" style="height:680px">
                <template #before>
                    <div class="q-pa-md">
                        <div class="text-h6 q-mb-md">Available Menu Items</div>
                        <q-tree :nodes="availableMenus" default-expand-all node-key="uuid">
                            <template v-slot:default-header="prop">
                                <div class="row items-center full-width">
                                    <q-icon :name="prop.node.icon || 'sym_o_menu'" class="q-mr-sm" size="sm" />
                                    <span>{{ prop.node.label }}</span>
                                    <q-space />
                                    <small v-if="prop.node.to" class="text-grey-6 q-mr-sm">{{ prop.node.to }}</small>
                                    <q-btn flat round dense size="sm" icon="sym_o_add" color="positive"
                                        @click.stop="addMenuToCustom(prop.node)">
                                        <q-tooltip>Add to My Menu</q-tooltip>
                                    </q-btn>
                                </div>
                            </template>
                        </q-tree>
                    </div>
                </template>

                <template #after>
                    <div class="q-pa-md">
                        <div class="text-h6 q-mb-md">My Custom Menu</div>

                        <!-- Action buttons -->
                        <q-card-actions class="q-mb-md q-gutter-xs" v-if="currentNodeDetail">
                            <template v-if="currentNodeDetail.type === 'root'">
                                <q-btn-dropdown v-bind="$light.getButtonProps({ label: 'Add' })" icon="sym_o_add"
                                    size="sm" color="primary">
                                    <q-list>
                                        <q-item clickable v-close-popup @click="createNewFolder">
                                            <q-item-section avatar>
                                                <q-icon name="sym_o_folder" color="orange" />
                                            </q-item-section>
                                            <q-item-section>
                                                <q-item-label>Add Folder</q-item-label>
                                            </q-item-section>
                                        </q-item>
                                        <q-item clickable v-close-popup @click="createNewSubItem">
                                            <q-item-section avatar>
                                                <q-icon name="sym_o_menu" />
                                            </q-item-section>
                                            <q-item-section>
                                                <q-item-label>Add Sub Item</q-item-label>
                                            </q-item-section>
                                        </q-item>
                                        <q-item clickable v-close-popup @click="addSeparator">
                                            <q-item-section avatar>
                                                <q-icon name="sym_o_more_horiz" color="grey" />
                                            </q-item-section>
                                            <q-item-section>
                                                <q-item-label>Add Separator</q-item-label>
                                            </q-item-section>
                                        </q-item>
                                    </q-list>
                                </q-btn-dropdown>
                            </template>
                            <template v-else>
                                <q-btn-dropdown v-bind="$light.getButtonProps({ label: 'Add' })" icon="sym_o_add"
                                    size="sm" color="primary">
                                    <q-list>
                                        <q-item clickable v-close-popup @click="createNewFolder">
                                            <q-item-section avatar>
                                                <q-icon name="sym_o_folder" color="orange" />
                                            </q-item-section>
                                            <q-item-section>
                                                <q-item-label>Add Folder</q-item-label>
                                            </q-item-section>
                                        </q-item>
                                        <q-item clickable v-close-popup @click="createNewSubItem">
                                            <q-item-section avatar>
                                                <q-icon name="sym_o_menu" />
                                            </q-item-section>
                                            <q-item-section>
                                                <q-item-label>Add Sub Item</q-item-label>
                                            </q-item-section>
                                        </q-item>
                                        <q-item clickable v-close-popup @click="addSeparator">
                                            <q-item-section avatar>
                                                <q-icon name="sym_o_more_horiz" color="grey" />
                                            </q-item-section>
                                            <q-item-section>
                                                <q-item-label>Add Separator</q-item-label>
                                            </q-item-section>
                                        </q-item>
                                    </q-list>
                                </q-btn-dropdown>

                                <l-btn @click="removeMenuItem(currentNodeDetail)" label="Delete" icon="sym_o_delete"
                                    size="sm" color="negative" />
                                <l-btn @click="moveUp(currentNodeDetail)" label="Move Up" icon="sym_o_arrow_upward"
                                    size="sm" />
                                <l-btn @click="moveDown(currentNodeDetail)" label="Move Down"
                                    icon="sym_o_arrow_downward" size="sm" />
                                <l-btn @click="moveToGroup" label="Move to..." icon="sym_o_drive_file_move" size="sm" />
                            </template>
                        </q-card-actions>

                        <!-- Menu tree -->
                        <q-tree :nodes="userMenus" default-expand-all v-model:selected="selectedNode" node-key="uuid"
                            ref="userMenuTree">
                            <template v-slot:default-header="prop">
                                <div class="row items-center full-width">
                                    <q-icon :name="prop.node.type === 'separator' ? 'sym_o_more_horiz' :
                                        prop.node.type === 'root' ? 'sym_o_account_tree' :
                                            prop.node.icon || 'sym_o_menu'" class="q-mr-sm" size="sm" :color="prop.node.type === 'separator' ? 'grey' :
                                                prop.node.type === 'root' ? 'primary' : undefined" />
                                    <span :class="{
                                        'text-grey-6': prop.node.type === 'separator',
                                        'text-primary': prop.node.type === 'root'
                                    }">
                                        {{ prop.node.label }}
                                    </span>
                                    <q-space />
                                    <small v-if="prop.node.to" class="text-grey-6">{{ prop.node.to }}</small>
                                </div>
                            </template>
                        </q-tree>

                        <!-- Current selected node detail settings -->
                        <div v-if="currentNodeDetail && currentNodeDetail.type !== 'root'" class="q-mt-lg">
                            <q-separator class="q-mb-md" />
                            <div class="text-subtitle1 q-mb-md">Menu Settings</div>

                            <template v-if="currentNodeDetail.type === 'separator'">
                                <div class="q-gutter-md">
                                    <l-checkbox label="Spaced Separator" v-model="currentNodeDetail.spaced" />
                                </div>
                            </template>

                            <template v-else>
                                <div class="q-gutter-md">
                                    <l-input label="Label" v-model="currentNodeDetail.label" />
                                    <l-input label="Route" v-model="currentNodeDetail.to" />
                                    <l-icon-picker label="Icon" v-model="currentNodeDetail.icon" />
                                </div>
                            </template>
                        </div>
                    </div>
                </template>
            </q-splitter>
        </l-card>
    </div>
</template>
