<script setup>
import { computed } from "vue";

import NavNodeBranch from "./NavNodeEditor.vue";

defineOptions({ name: "NavNodeEditor" });

import Button from "primevue/button";
import Checkbox from "primevue/checkbox";
import Dropdown from "primevue/dropdown";
import InputText from "primevue/inputtext";
import TabPanel from "primevue/tabpanel";
import TabView from "primevue/tabview";
import Tag from "primevue/tag";

const props = defineProps({
  node: { type: Object, required: true },
  modules: { type: Array, default: () => [] },
  permissions: { type: Array, default: () => [] },
  depth: { type: Number, default: 0 },
  /** Lighter panel when nested under a parent’s “Sub-items” list */
  embedded: { type: Boolean, default: false },
});

const emit = defineEmits(["remove"]);

const moduleOptions = computed(() => [
  { label: "(none)", value: null },
  ...props.modules.map((m) => ({
    label: `${m.label} (${m.slug})`,
    value: m.slug,
  })),
]);

const permissionOptions = computed(() => [
  { label: "(none)", value: null },
  ...props.permissions.map((p) => ({ label: p, value: p })),
]);

const moduleSlugModel = computed({
  get() {
    return props.node.module_slug ?? null;
  },
  set(v) {
    props.node.module_slug = v;
  },
});

const permissionModel = computed({
  get() {
    return props.node.permission ?? null;
  },
  set(v) {
    props.node.permission = v;
  },
});

function ensureChildren() {
  if (!Array.isArray(props.node.children)) {
    props.node.children = [];
  }
}

function addChild() {
  ensureChildren();
  props.node.children.push({
    key: `nav-${Date.now()}`,
    label: "New item",
    route: "",
    icon: "",
    permission: null,
    description: "",
    module_slug: null,
    is_header: false,
    pinned_bottom: false,
    children: [],
  });
}

function removeChild(index) {
  ensureChildren();
  props.node.children.splice(index, 1);
}

function removeSelf() {
  emit("remove");
}

const isRoot = computed(() => props.node.key === "root");

const childCount = computed(() => (props.node.children || []).length);

const hierarchyTag = computed(() => {
  if (isRoot.value) {
    return { label: "Root", severity: "info" };
  }
  if (props.depth <= 1) {
    return { label: "Main sidebar item", severity: "success" };
  }
  return { label: "Sub-sidebar link", severity: "secondary" };
});

const propertiesTabLabel = computed(() =>
  isRoot.value ? "Overview" : "Properties",
);

const subItemsTabLabel = computed(() => `Sub-items (${childCount.value})`);

const panelWrapperClass = computed(() => {
  if (props.embedded) {
    return "rounded-lg bg-surface-50 dark:bg-surface-900/40 border border-surface-200 dark:border-surface-700 p-3 mb-2";
  }
  return "border border-surface-200 dark:border-surface-700 rounded-lg p-4 mb-3 bg-surface-0 dark:bg-surface-950 shadow-[0_1px_2px_rgba(0,0,0,0.04)] dark:shadow-none";
});

const indentStyle = computed(() => {
  if (props.embedded || !props.depth) {
    return {};
  }
  const px = Math.min(props.depth * 12, 48);
  return { marginLeft: `${px}px` };
});
</script>

<template>
  <div :class="panelWrapperClass" :style="indentStyle">
    <div class="flex flex-wrap items-start justify-between gap-3 mb-3">
      <div class="flex flex-wrap items-center gap-2 min-w-0">
        <span class="font-semibold text-surface-900 dark:text-surface-0 truncate">
          {{ isRoot ? "Navigation root" : (node.label || "Untitled") }}
        </span>
        <Tag
          :value="hierarchyTag.label"
          :severity="hierarchyTag.severity"
          class="text-xs shrink-0"
        />
        <code
          v-if="!isRoot"
          class="text-xs text-surface-500 dark:text-surface-400 font-normal truncate max-w-[12rem] sm:max-w-xs"
          >{{ node.key }}</code
        >
      </div>
      <Button
        v-if="!isRoot"
        icon="pi pi-trash"
        severity="danger"
        text
        rounded
        aria-label="Remove node"
        type="button"
        @click="removeSelf"
      />
    </div>

    <TabView class="nav-node-editor-tabs" :lazy="true">
      <TabPanel :header="propertiesTabLabel">
        <div v-if="isRoot" class="pt-2">
          <p
            class="text-sm text-surface-600 dark:text-surface-400 mb-0 leading-relaxed"
          >
            This node is the root of the sidebar tree. Open
            <strong class="text-surface-800 dark:text-surface-200">Sub-items</strong>
            to edit top-level entries (Dashboard, Customers, Settings, …). Each
            entry can have its own nested links for the vertical sub-sidebar.
          </p>
        </div>
        <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-3 pt-2">
          <label class="flex flex-col gap-1 text-sm">
            <span class="text-surface-600 dark:text-surface-400">Key</span>
            <InputText v-model="node.key" class="w-full" />
          </label>
          <label class="flex flex-col gap-1 text-sm">
            <span class="text-surface-600 dark:text-surface-400">Label</span>
            <InputText v-model="node.label" class="w-full" />
          </label>
          <label class="flex flex-col gap-1 text-sm md:col-span-2">
            <span class="text-surface-600 dark:text-surface-400"
              >Route path</span
            >
            <InputText
              v-model="node.route"
              placeholder="/dashboard"
              class="w-full"
            />
          </label>
          <label class="flex flex-col gap-1 text-sm md:col-span-2">
            <span class="text-surface-600 dark:text-surface-400"
              >Icon class</span
            >
            <InputText
              v-model="node.icon"
              placeholder="pi pi-fw pi-home"
              class="w-full"
            />
          </label>
          <label class="flex flex-col gap-1 text-sm md:col-span-2">
            <span class="text-surface-600 dark:text-surface-400"
              >Description</span
            >
            <InputText v-model="node.description" class="w-full" />
          </label>
          <label class="flex flex-col gap-1 text-sm">
            <span class="text-surface-600 dark:text-surface-400">Module</span>
            <Dropdown
              v-model="moduleSlugModel"
              :options="moduleOptions"
              option-label="label"
              option-value="value"
              placeholder="Optional"
              class="w-full"
              show-clear
            />
          </label>
          <label class="flex flex-col gap-1 text-sm">
            <span class="text-surface-600 dark:text-surface-400"
              >Permission</span
            >
            <Dropdown
              v-model="permissionModel"
              :options="permissionOptions"
              option-label="label"
              option-value="value"
              placeholder="Optional"
              class="w-full"
              filter
              show-clear
            />
          </label>
          <div class="flex flex-wrap gap-4 items-center md:col-span-2">
            <label class="flex items-center gap-2 text-sm">
              <Checkbox v-model="node.is_header" binary />
              Section header
            </label>
            <label class="flex items-center gap-2 text-sm">
              <Checkbox v-model="node.pinned_bottom" binary />
              Pin to bottom
            </label>
          </div>
        </div>
      </TabPanel>

      <TabPanel :header="subItemsTabLabel">
        <div class="flex flex-col gap-2 pt-2">
          <p
            v-if="!childCount"
            class="text-sm text-surface-500 dark:text-surface-400 mb-0"
          >
            No child links yet. Add one to build nested sidebar or sub-sidebar
            entries.
          </p>
          <details
            v-for="(child, idx) in node.children || []"
            v-show="child.module_is_enabled !== false"
            :key="child.key || idx"
            class="rounded-lg border border-surface-200 dark:border-surface-700 bg-surface-0 dark:bg-surface-950 overflow-hidden group"
          >
            <summary
              class="flex flex-wrap items-center justify-between gap-2 cursor-pointer select-none list-none px-3 py-2.5 text-sm bg-surface-50 dark:bg-surface-900/60 hover:bg-surface-100 dark:hover:bg-surface-800/80 transition-colors"
            >
              <span class="font-medium text-surface-900 dark:text-surface-0">
                {{ child.label || "Untitled" }}
                <span
                  class="text-xs font-normal text-surface-500 dark:text-surface-400 ml-1"
                  >{{ child.key }}</span
                >
              </span>
              <span
                class="text-xs text-surface-500 dark:text-surface-400 shrink-0"
              >
                Click to expand
              </span>
            </summary>
            <div
              class="border-t border-surface-200 dark:border-surface-700 p-2"
            >
              <NavNodeBranch
                :node="child"
                :modules="modules"
                :permissions="permissions"
                :depth="depth + 1"
                embedded
                @remove="removeChild(idx)"
              />
            </div>
          </details>
          <Button
            label="Add child"
            icon="pi pi-plus"
            severity="secondary"
            outlined
            class="mt-1 self-start"
            type="button"
            @click="addChild"
          />
        </div>
      </TabPanel>
    </TabView>
  </div>
</template>

<style scoped>
.nav-node-editor-tabs :deep(.p-tabview-nav) {
  flex-wrap: wrap;
}
.nav-node-editor-tabs :deep(summary::-webkit-details-marker) {
  display: none;
}
</style>
