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

import Button from "primevue/button";
import Message from "primevue/message";

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

import NavNodeEditorSelf 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?.data) ? modsRes.data.data : [];
  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). Changes apply after
      save.
    </p>
    <Message v-if="error" severity="error" class="mb-4" :closable="false">
      {{ error }}
    </Message>
    <div class="flex flex-wrap gap-2 mb-6">
      <Button
        label="Reload"
        icon="pi pi-refresh"
        severity="secondary"
        outlined
        :loading="loading"
        type="button"
        @click="loadTree"
      />
      <Button
        label="Save navigation"
        icon="pi pi-save"
        :loading="saving"
        :disabled="loading || !rootNode"
        type="button"
        @click="save"
      />
    </div>
    <div v-if="rootNode">
      <NavNodeEditorSelf
        :node="rootNode"
        :modules="modules"
        :permissions="permissions"
        :depth="0"
      />
    </div>
  </div>
</template>
