<script setup>
import { api, ensureCsrf } from "../../services/api.js";
import { useNavigation } from "../../composables/useNavigation.js";

import BaseAlert from "../../components/base/BaseAlert.vue";
import BaseButton from "../../components/base/BaseButton.vue";

import { cloneDeepForSave, normalizeTreeFromApi } from "./superadminNavigationTree.js";

import NavNodeEditor from "./NavNodeEditor.vue";
import { onMounted, ref } from "vue";

const loading = ref(false);
const saving = ref(false);
const error = ref("");
const tree = ref([]);
const modules = ref([]);
const permissions = ref([]);
const rootNode = ref(null);

const { fetchNavigation } = useNavigation();

async function loadModulesAndPermissions() {
  await ensureCsrf();
  const [modsRes, permRes] = await Promise.all([
    api.get("/api/superadmin/modules"),
    api.get("/api/permissions"),
  ]);
  modules.value = Array.isArray(modsRes.data?.modules) ? modsRes.data.modules : [];
  permissions.value = Array.isArray(permRes.data?.data)
    ? permRes.data.data
    : [];
}

async function loadTree() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    await loadModulesAndPermissions();
    const { data } = await api.get("/api/superadmin/navigation-tree");
    const normalized = normalizeTreeFromApi(data?.tree ?? []);
    tree.value = normalized;
    rootNode.value = normalized[0] ?? null;
  } catch (e) {
    error.value =
      e?.response?.data?.message || "Could not load navigation tree.";
    tree.value = [];
    rootNode.value = null;
  } finally {
    loading.value = false;
  }
}

async function save() {
  if (!rootNode.value) return;
  saving.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    const payload = {
      tree: cloneDeepForSave([rootNode.value]),
    };
    await api.put("/api/superadmin/navigation-tree", payload);
    await fetchNavigation();
    await loadTree();
  } catch (e) {
    const msg =
      e?.response?.data?.message ||
      (Array.isArray(e?.response?.data?.errors?.tree)
        ? e.response.data.errors.tree.join(" ")
        : null);
    error.value = msg || "Save failed. Check validation.";
  } finally {
    saving.value = false;
  }
}

onMounted(() => {
  loadTree();
});
</script>

<template>
  <div>
    <h1 class="title-h5 mb-4">Navigation structure</h1>
    <p class="body-small text-surface-600 dark:text-surface-400 mb-6">
      Edit sidebar entries (labels, routes, permissions). Sub-items are shown
      first; expand a row to edit nested links. For each node, Properties below
      lists key, route, icon, and gates. Save to apply.
    </p>
    <BaseAlert v-if="error" severity="error" class="mb-4" :closable="false">
      {{ error }}
    </BaseAlert>
    <BaseAlert
      v-if="!loading && !error && !rootNode"
      severity="warn"
      class="mb-4"
      :closable="false"
    >
      No navigation tree was returned (empty <code class="text-sm px-1">tree</code
      >). Usually that means rows were never seeded in
      <code class="text-sm px-1">maestro_navigation_nodes</code>. Run migrations,
      then:
      <code class="text-sm px-1 rounded bg-surface-100 dark:bg-surface-800"
        >php artisan db:seed --class=&quot;Maestro\\Core\\Database\\Seeders\\ModuleAndNavigationSeeder&quot;</code
      >
      — that creates the default root item and sidebar structure.
    </BaseAlert>
    <div class="flex flex-wrap gap-2 mb-6">
      <BaseButton
        label="Reload"
        icon="refresh"
        variant="secondary"
        outlined
        :loading="loading"
        type="button"
        @click="loadTree"
      />
      <BaseButton
        label="Save navigation"
        icon="save"
        variant="primary"
        :loading="saving"
        :disabled="loading || !rootNode"
        type="button"
        @click="save"
      />
    </div>
    <div v-if="rootNode">
      <NavNodeEditor
        :node="rootNode"
        :modules="modules"
        :permissions="permissions"
        :depth="0"
      />
    </div>
  </div>
</template>
