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

import Button from "primevue/button";
import Column from "primevue/column";
import DataTable from "primevue/datatable";
import InputSwitch from "primevue/inputswitch";
import Message from "primevue/message";

import { onMounted, ref } from "vue";

const loading = ref(false);
const savingSlug = ref("");
const error = ref("");
const modules = ref([]);

async function load() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    const { data } = await api.get("/api/superadmin/modules");
    modules.value = Array.isArray(data?.data) ? data.data : [];
  } catch (e) {
    error.value =
      e?.response?.data?.message || "Could not load modules. Forbidden?";
    modules.value = [];
  } finally {
    loading.value = false;
  }
}

async function toggle(row, nextEnabled) {
  savingSlug.value = row.slug;
  error.value = "";
  try {
    await ensureCsrf();
    await api.patch(`/api/superadmin/modules/${row.slug}`, {
      is_enabled: nextEnabled,
    });
    row.is_enabled = nextEnabled;
    await hydrateUser();
  } catch (e) {
    error.value =
      e?.response?.data?.message || "Could not update module. Try again.";
    row.is_enabled = !nextEnabled;
  } finally {
    savingSlug.value = "";
  }
}

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

<template>
  <div>
    <h1 class="title-h5 mb-4">Feature modules</h1>
    <p class="body-small text-surface-600 dark:text-surface-400 mb-6">
      Disabled modules hide navigation entries and block direct URLs for that
      module.
    </p>
    <Message v-if="error" severity="error" class="mb-4" :closable="false">
      {{ error }}
    </Message>
    <div class="flex justify-end mb-3">
      <Button
        label="Refresh"
        icon="pi pi-refresh"
        severity="secondary"
        outlined
        :loading="loading"
        @click="load"
      />
    </div>
    <DataTable :value="modules" data-key="slug" striped-rows>
      <Column field="label" header="Module" />
      <Column field="slug" header="Slug" />
      <Column header="Enabled" style="width: 8rem">
        <template #body="{ data }">
          <InputSwitch
            :model-value="Boolean(data.is_enabled)"
            :disabled="loading || savingSlug === data.slug"
            @update:model-value="(v) => toggle(data, v)"
          />
        </template>
      </Column>
    </DataTable>
  </div>
</template>
