<script setup>
import { ref, computed, inject } from "vue";
import { m, q } from "#imports";
import { useQuasar, Dialog } from "quasar";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const quasar = useQuasar();
const $q = quasar;
const { app: { customMenus } } = await q({
  app: {
    customMenus: true
  }
});
const menus = ref([
  {
    label: "[Root]",
    uuid: "ROOT",
    children: customMenus.map((m2) => {
      m2.parent = "ROOT";
      return m2;
    }),
    type: "root"
  }
]);
const selected = ref("ROOT");
const tree1 = ref(null);
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 onReload = async () => {
  const data = await q({
    app: {
      customMenus: true
    }
  });
  menus.value[0].children = data.app.customMenus;
};
const onAddChild = (node) => {
  $q.dialog({
    title: t("Add child menu"),
    message: t("Enter menu label"),
    prompt: {
      model: ""
    },
    cancel: true,
    persistent: true
  }).onOk((data) => {
    if (data === "") return;
    node.children.push({
      label: data,
      uuid: getUUID(),
      parent: node.uuid,
      children: [],
      icon: "sym_o_link"
    });
    tree1.value.setExpanded(selected.value, true);
  });
};
const onRemove = (node) => {
  const parent = node.parent;
  if (parent) {
    const parentNode = tree1.value.getNodeByKey(parent);
    parentNode.children = parentNode.children.filter((item) => item.uuid !== node.uuid);
    selected.value = parent;
  } else {
    menus.value = menus.value.filter((item) => item.uuid !== node.uuid);
    selected.value = null;
  }
};
const splitterModel = ref(20);
const selectedNode = computed(() => {
  if (selected.value == "ROOT") return menus.value[0];
  return tree1.value.getNodeByKey(selected.value);
});
const reloadMenu = inject("reloadMenu");
const onSave = () => {
  quasar.dialog({
    title: "Save Menu",
    message: "Are you sure to save menu?",
    cancel: true,
    persistent: true
  }).onOk(async () => {
    if (await m("updateAppMenus", {
      data: menus.value[0].children
    })) {
      quasar.notify({
        message: "Menu saved",
        color: "positive",
        icon: "check",
        position: "top",
        timeout: 1e3
      });
    }
    reloadMenu();
  });
};
const showMove = ref(false);
const onMove = () => {
  showMove.value = true;
};
const moveTarget = ref(null);
const onMoveConfirm = () => {
  const selectedNode2 = tree1.value.getNodeByKey(selected.value);
  const newNode = JSON.parse(JSON.stringify(selectedNode2));
  onRemove(selectedNode2);
  newNode.parent = moveTarget.value;
  let targetNode = tree1.value.getNodeByKey(moveTarget.value);
  targetNode.children = targetNode.children || [];
  targetNode.children.push(newNode);
  tree1.value.setExpanded(moveTarget.value, true);
  showMove.value = false;
};
const getParentNode = (node) => {
  if (!node.parent) return {
    children: menus.value
  };
  return tree1.value.getNodeByKey(node.parent);
};
const onMoveUp = (node) => {
  const parent = getParentNode(node);
  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 onMoveDown = (node) => {
  const parent = getParentNode(node);
  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 onAddChildMenu = (node, type) => {
  type = type.charAt(0).toUpperCase() + type.slice(1);
  node.children.push({
    label: type,
    uuid: getUUID(),
    parent: node.uuid,
    icon: "sym_o_" + type.toLowerCase(),
    children: []
  });
};
const onAddSeparator = (node) => {
  node.children.push({
    label: "[Separator]",
    uuid: getUUID(),
    parent: node.uuid,
    children: [],
    type: "separator",
    spaced: true
  });
};
const onAddHeader = (node) => {
  node.children.push({
    label: "[Header]",
    uuid: getUUID(),
    parent: node.uuid,
    children: [],
    type: "header"
  });
};
const menusOnly = computed(() => {
  return menus.value.filter((item) => !item.type);
});
</script>

<template>
    <l-page>
        <q-dialog v-model="showMove">
            <l-card>
                <q-card-section>
                    <q-tree :nodes="menus" default-expand-all v-model:selected="moveTarget" node-key="uuid"
                        ref="tree2" />
                </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="onMoveConfirm" />
                    <!-- q-btn flat label="Move to root" color="primary" @click="onMoveToRoot" /-->
                </q-card-actions>
            </l-card>
        </q-dialog>

        <l-card>
            <q-card-actions class="q-gutter-y-sm">
                <l-btn @click="onSave" label="Save" icon="sym_o_save" />
                <l-btn @click="onReload" label="Reload" icon="sym_o_refresh" />

                <template v-if="selectedNode">

                    <template v-if="selectedNode.type == 'root'">
                        <l-btn @click="onAddChild(selectedNode)" label="Add" icon="sym_o_add" />
                        <l-btn @click="onAddHeader(selectedNode)" label="Add Header" icon="sym_o_add" />
                        <l-btn @click="onAddSeparator(selectedNode)" label="Add Separator" icon="sym_o_add" />
                    </template>
                    <template v-else>
                        <q-btn-dropdown v-bind="$light.getButtonProps({ label: 'Add' })" icon="sym_o_add"
                            color="primary">
                            <q-list>
                                <q-item clickable v-close-popup @click="onAddChild(selectedNode)">
                                    <q-item-section>
                                        <q-item-label>Child</q-item-label>
                                    </q-item-section>
                                </q-item>
                                <q-item clickable v-close-popup @click="onAddHeader(selectedNode)">
                                    <q-item-section>
                                        <q-item-label>Header</q-item-label>
                                    </q-item-section>
                                </q-item>
                                <q-item clickable v-close-popup @click="onAddSeparator(selectedNode)">
                                    <q-item-section>
                                        <q-item-label>Separator</q-item-label>
                                    </q-item-section>
                                </q-item>

                            </q-list>
                        </q-btn-dropdown>

                        <l-btn @click="onRemove(selectedNode)" label="Remove" icon="sym_o_remove" />

                        <l-btn @click="onMove(selectedNode)" label="Move" icon="sym_o_move" />

                        <l-btn @click="onMoveUp(selectedNode)" label="Up" icon="sym_o_arrow_upward" />

                        <l-btn @click="onMoveDown(selectedNode)" label="Down" icon="sym_o_arrow_downward" />

                        <q-btn-dropdown v-bind="$light.getButtonProps({ label: 'Add menus' })" icon="sym_o_add"
                            color="primary">
                            <q-list>
                                <q-item clickable v-close-popup @click="onAddChildMenu(selectedNode, 'list')">
                                    <q-item-section>
                                        <q-item-label>List</q-item-label>
                                    </q-item-section>
                                </q-item>

                                <q-item clickable v-close-popup @click="onAddChildMenu(selectedNode, 'add')">
                                    <q-item-section>
                                        <q-item-label>Add</q-item-label>
                                    </q-item-section>
                                </q-item>

                            </q-list>
                        </q-btn-dropdown>
                    </template>
                </template>
            </q-card-actions>
            <q-splitter v-model="splitterModel" style="height:680px">
                <template #before>

                    <q-tree :nodes="menus" default-expand-all v-model:selected="selected" node-key="uuid" ref="tree1" />
                </template>

                <template #after v-if="selected">
                    <q-card-section>
                        <template v-if="!selectedNode.type">
                            <div class="q-gutter-md">
                                <l-input label="Label" v-model="selectedNode.label" />
                                <l-input label="To" v-model="selectedNode.to" />
                                <l-input label="Icon" v-model="selectedNode.icon"
                                    hint="example: sym_o_add, fas fa-ambulance, mdi-alert-circle-outline">
                                    <template #append>
                                        <l-icon-picker v-model="selectedNode.icon" dense />
                                    </template>
                                </l-input>
                                <l-input label="Permission" v-model="selectedNode.permission" />
                                <l-input label="UUID" v-model="selectedNode.uuid" readonly />
                            </div>

                            <div>
                                <ul>
                                    <li>
                                        <a href="https://fonts.google.com/icons" target="_blank">Material Icons</a>
                                    </li>
                                    <li>
                                        <a href="https://fontawesome.com/search" target="_blank">Font Awesome</a>
                                    </li>

                                    <li>
                                        <a href="https://materialdesignicons.com/" target="_blank">Material Design
                                            Icons</a>
                                    </li>
                                    <li>
                                        <a href="https://quasar.dev/vue-components/icon#webfont-usage"
                                            target="_blank">Quasar
                                            Icons</a>
                                    </li>
                                </ul>

                            </div>

                        </template>

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

                            </div>
                        </template>

                        <template v-if="selectedNode.type == 'header'">
                            <div class="q-gutter-md">
                                <l-input label="Label" v-model="selectedNode.label" />
                            </div>
                        </template>
                    </q-card-section>

                </template>

            </q-splitter>

        </l-card>

    </l-page>
</template>
