<script setup>
import Button from "primevue/button";
import Message from "primevue/message";
import Tag from "primevue/tag";
import { useToast } from "primevue/usetoast";
import { onMounted, reactive, ref } from "vue";

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

const toast = useToast();

const loading = ref(false);
const activatingSlug = ref("");
const error = ref("");
const checkedAt = ref("");
const modules = ref([]);
/** @type {Record<string, boolean>} */
const expanded = reactive({});

const SIGNAL_LABELS = {
  config: "Config",
  database: "Database",
  seeder: "Seeder",
  routes: "Routes",
};

const SIGNAL_KEYS = ["config", "database", "seeder", "routes"];

async function load() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    const { data } = await api.get("/api/superadmin/modules");
    checkedAt.value = data?.checked_at ?? "";
    modules.value = Array.isArray(data?.modules) ? data.modules : [];
  } catch (e) {
    error.value =
      e?.response?.data?.message ?? "Kon modules niet laden (geen toestemming?).";
    modules.value = [];
  } finally {
    loading.value = false;
  }
}

function toggleDetail(slug) {
  expanded[slug] = !expanded[slug];
}

async function activate(mod) {
  activatingSlug.value = mod.slug;
  error.value = "";
  try {
    await ensureCsrf();
    await api.post(`/api/superadmin/modules/${mod.slug}/activate`);
    mod.is_enabled = true;
    await hydrateUser();
    toast.add({
      severity: "success",
      summary: "Module geactiveerd",
      detail: `${mod.label} is nu actief.`,
      life: 3000,
    });
    await load();
  } catch (e) {
    const msg =
      e?.response?.data?.message ?? "Activeren mislukt. Probeer opnieuw.";
    error.value = msg;
    toast.add({ severity: "error", summary: "Activeren mislukt", detail: msg, life: 5000 });
  } finally {
    activatingSlug.value = "";
  }
}

async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    toast.add({
      severity: "success",
      summary: "Gekopieerd",
      detail: "Commando gekopieerd.",
      life: 2000,
    });
  } catch {
    toast.add({
      severity: "error",
      summary: "Kopiëren mislukt",
      detail: "Klembord niet beschikbaar.",
      life: 4000,
    });
  }
}

function signalClass(status) {
  if (status === "ok") return "bg-green-500";
  if (status === "warn") return "bg-amber-400";
  return "bg-red-500";
}

function signalSeverity(status) {
  if (status === "ok") return "success";
  if (status === "warn") return "warn";
  return "danger";
}

function signalLabel(status) {
  if (status === "ok") return "OK";
  if (status === "warn") return "Let op";
  return "Fout";
}

function overallSeverity(overall) {
  return signalSeverity(overall ?? "fail");
}

function overallLabel(overall) {
  if (overall === "ok") return "Klaar om te activeren";
  if (overall === "warn") return "Aandacht nodig";
  return "Geblokkeerd";
}

function canActivate(mod) {
  const h = mod.health;
  return (
    !mod.is_enabled &&
    h.config.status !== "fail" &&
    h.database.status !== "fail"
  );
}

onMounted(load);
</script>

<template>
  <div>
    <div class="flex flex-wrap items-start justify-between gap-3 mb-6">
      <div>
        <h1 class="title-h5 mb-1">Modules</h1>
        <p class="body-small text-surface-600 dark:text-surface-400">
          Controleer per module en activeer na migraties en seeders. Eenmaal actief kan een module
          niet meer worden uitgeschakeld. Basisinstallatie staat onder
          <span class="font-medium text-surface-700 dark:text-surface-300"
            >Installatiecontrole</span
          >.
        </p>
      </div>
      <Button
        label="Vernieuwen"
        icon="pi pi-refresh"
        severity="secondary"
        outlined
        :loading="loading"
        @click="load"
      />
    </div>

    <Message v-if="error" severity="error" class="mb-6" :closable="false">
      {{ error }}
    </Message>

    <div
      v-if="!loading && modules.length === 0"
      class="text-center py-12 text-surface-500"
    >
      Geen modules gevonden. Voer migraties en seeders uit.
    </div>

    <div class="flex flex-col gap-4">
      <div
        v-for="mod in modules"
        :key="mod.slug"
        class="rounded-xl border overflow-hidden flex flex-col"
        :class="
          mod.is_enabled
            ? 'border-green-300 dark:border-green-800'
            : 'border-surface-200 dark:border-surface-700'
        "
      >
        <!-- Header: hoofdstatus + uitklappen -->
        <button
          type="button"
          class="w-full px-4 py-3 flex flex-wrap items-center justify-between gap-3 text-left transition-colors"
          :class="
            mod.is_enabled
              ? 'bg-green-50 dark:bg-green-950/30'
              : 'bg-surface-50 dark:bg-surface-900'
          "
          @click="toggleDetail(mod.slug)"
        >
          <div class="flex items-center gap-2 min-w-0">
            <span
              class="inline-flex h-2.5 w-2.5 rounded-full shrink-0"
              :class="signalClass(mod.health.overall)"
            />
            <span class="font-semibold text-surface-800 dark:text-surface-100 truncate">
              {{ mod.label }}
            </span>
          </div>
          <div class="flex items-center gap-2 shrink-0">
            <Tag
              v-if="mod.is_enabled"
              severity="success"
              value="Actief"
              class="text-xs"
            />
            <Tag
              v-else
              :severity="overallSeverity(mod.health.overall)"
              :value="overallLabel(mod.health.overall)"
              class="text-xs"
            />
            <i
              class="pi text-surface-500"
              :class="expanded[mod.slug] ? 'pi-chevron-up' : 'pi-chevron-down'"
            />
          </div>
        </button>

        <!-- Afhankelijkheden -->
        <div
          v-if="mod.dependencies.length || mod.dependents.length"
          class="px-4 py-2 border-t border-surface-100 dark:border-surface-800 flex flex-wrap gap-x-4 gap-y-1 bg-surface-0 dark:bg-surface-950/30"
        >
          <span
            v-if="mod.dependencies.length"
            class="text-xs text-surface-500 dark:text-surface-400"
          >
            Vereist:
            <span
              v-for="dep in mod.dependencies"
              :key="dep"
              class="font-medium text-surface-700 dark:text-surface-300"
            >
              {{ dep }}
            </span>
          </span>
          <span
            v-if="mod.dependents.length"
            class="text-xs text-surface-400 dark:text-surface-500"
          >
            Gebruikt door:
            <template v-for="(dep, i) in mod.dependents" :key="dep">
              <span v-if="i > 0">, </span>
              <span class="font-medium">{{ dep }}</span>
            </template>
          </span>
        </div>

        <!-- Uitklap: elk signaal + commando's -->
        <div
          v-show="expanded[mod.slug]"
          class="px-4 py-4 border-t border-surface-100 dark:border-surface-800 space-y-3 bg-surface-0 dark:bg-surface-900"
        >
          <div
            v-for="key in SIGNAL_KEYS"
            :key="key"
            class="rounded-lg border border-surface-100 dark:border-surface-800 bg-surface-50/90 dark:bg-surface-950/50 px-3 py-2.5"
          >
            <div class="flex flex-wrap items-center gap-2 mb-1">
              <span
                class="inline-flex h-2 w-2 rounded-full shrink-0"
                :class="signalClass(mod.health[key]?.status)"
              />
              <span class="text-sm font-medium text-surface-800 dark:text-surface-100">
                {{ SIGNAL_LABELS[key] }}
              </span>
              <Tag
                :severity="signalSeverity(mod.health[key]?.status)"
                :value="signalLabel(mod.health[key]?.status)"
                class="text-xs"
              />
            </div>
            <p class="text-xs text-surface-600 dark:text-surface-400 ml-4 mb-1">
              {{ mod.health[key]?.detail }}
            </p>
            <div
              v-if="mod.health[key]?.commands?.length"
              class="ml-4 mt-2 flex flex-col gap-2"
            >
              <div
                v-for="cmd in mod.health[key].commands"
                :key="cmd"
                class="flex items-start gap-1 max-w-full"
              >
                <code
                  class="text-xs px-2 py-1.5 rounded bg-surface-100 dark:bg-surface-800 break-all flex-1 min-w-0"
                >
                  {{ cmd }}
                </code>
                <Button
                  icon="pi pi-copy"
                  severity="secondary"
                  text
                  rounded
                  size="small"
                  class="shrink-0"
                  v-tooltip.bottom="'Kopiëren'"
                  @click="copyText(cmd)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- Actie: zelfde kaart -->
        <div
          v-if="!mod.is_enabled"
          class="px-4 py-3 border-t border-surface-100 dark:border-surface-800 bg-surface-50/50 dark:bg-surface-950/20"
        >
          <Button
            label="Module activeren"
            icon="pi pi-check-circle"
            :disabled="!canActivate(mod) || activatingSlug === mod.slug"
            :loading="activatingSlug === mod.slug"
            class="w-full"
            v-tooltip.top="
              !canActivate(mod)
                ? 'Los config- en databaseproblemen eerst op (zie uitklap hierboven)'
                : null
            "
            @click="activate(mod)"
          />
        </div>
        <div
          v-else
          class="px-4 py-2.5 border-t border-green-100 dark:border-green-900/30 bg-green-50/40 dark:bg-green-950/20"
        >
          <p class="text-xs text-green-700 dark:text-green-400">
            Module is actief en zichtbaar voor gebruikers met het juiste recht.
          </p>
        </div>
      </div>
    </div>

    <p v-if="checkedAt && !loading" class="text-xs text-surface-400 mt-6">
      Laatst gecontroleerd {{ checkedAt }}
    </p>
  </div>
</template>
