<script setup>
import BaseAlert from "../../components/base/BaseAlert.vue";
import BaseButton from "../../components/base/BaseButton.vue";
import BaseSelect from "../../components/base/BaseSelect.vue";
import BaseTag from "../../components/base/BaseTag.vue";
import BaseToggleSwitch from "../../components/base/BaseToggleSwitch.vue";
import {
  hydrateAppSettings,
  persistPublicPageSettings,
  publicPageSettings,
} from "../../composables/useAppSettings";
import { useBaseToast } from "../../composables/useBaseToast.js";
import { api, apiErrorDetail, ensureCsrf } from "../../services/api.js";
import { computed, onMounted, ref } from "vue";

const toast = useBaseToast();

const loading = ref(false);
const saving = ref(false);
const error = ref("");
const status = ref(null);

const enabled = ref(false);
const mode = ref("core_default");

const modeOptions = [
  { label: "Standaard CORE-pagina", value: "core_default" },
  { label: "Eigen klantpagina (override)", value: "customer_override" },
];

const canSave = computed(
  () =>
    enabled.value !== Boolean(publicPageSettings.enabled) ||
    mode.value !== String(publicPageSettings.mode || "core_default"),
);

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

function signalLabel(current) {
  if (current === "ok") return "OK";
  if (current === "warn") return "Aandacht";
  return "Actie nodig";
}

async function load() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    await hydrateAppSettings();
    enabled.value = Boolean(publicPageSettings.enabled);
    mode.value =
      publicPageSettings.mode === "customer_override"
        ? "customer_override"
        : "core_default";

    const { data } = await api.get("/api/superadmin/public-page-health");
    status.value = data?.data ?? null;
  } catch (e) {
    error.value =
      e?.response?.data?.message ??
      "Publieke homepage kon niet geladen worden (geen toestemming of serverfout).";
    status.value = null;
  } finally {
    loading.value = false;
  }
}

async function save() {
  saving.value = true;
  error.value = "";
  try {
    await persistPublicPageSettings({
      enabled: enabled.value,
      mode: mode.value,
      rootMode: enabled.value ? "public" : "login",
    });
    await load();
    toast.add({
      severity: "success",
      summary: "Opgeslagen",
      detail: "Publieke homepage-instellingen zijn bijgewerkt.",
      life: 3000,
    });
  } catch (e) {
    const detail = apiErrorDetail(e);
    error.value = detail;
    toast.add({
      severity: "error",
      summary: "Opslaan mislukt",
      detail,
      life: 6000,
    });
  } finally {
    saving.value = false;
  }
}

async function copyText(text, kind = "Commando") {
  try {
    await navigator.clipboard.writeText(text);
    toast.add({
      severity: "success",
      summary: "Gekopieerd",
      detail: `${kind} is naar het klembord gekopieerd.`,
      life: 2200,
    });
  } catch {
    toast.add({
      severity: "error",
      summary: "Kopiëren mislukt",
      detail: "Klembord niet beschikbaar in deze context.",
      life: 4200,
    });
  }
}

onMounted(load);
</script>

<template>
  <div class="flex flex-col gap-6">
    <div>
      <h1 class="title-h5 mb-1">Publieke homepage</h1>
      <p class="body-small text-surface-600 dark:text-surface-400">
        Beheer de instellingen voor de publieke Vue-pagina op
        <code class="text-xs px-1 rounded bg-surface-100 dark:bg-surface-800">
          /
        </code>
        . Toggle uit = redirect naar <code class="text-xs px-1 rounded bg-surface-100 dark:bg-surface-800">/auth/login</code>.
        Toggle aan = root (<code class="text-xs px-1 rounded bg-surface-100 dark:bg-surface-800">/</code>) toont de publieke homepage.
      </p>
    </div>

    <BaseAlert v-if="error" severity="error" :closable="false">
      {{ error }}
    </BaseAlert>

    <section
      class="rounded-lg border border-surface-200 dark:border-surface-700 p-4 flex flex-col gap-5"
    >
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 items-start">
        <BaseToggleSwitch
          v-model="enabled"
          label="Publieke homepage inschakelen"
        />
        <BaseSelect
          v-model="mode"
          label="Pagina type"
          :options="modeOptions"
          option-label="label"
          option-value="value"
          :show-clear="false"
          :disabled="!enabled"
        />
      </div>

      <div class="flex flex-wrap items-center gap-3">
        <BaseButton
          label="Opslaan"
          icon="save"
          variant="primary"
          :disabled="!canSave || loading || saving"
          :loading="saving"
          @click="save"
        />
        <BaseButton
          label="Vernieuwen"
          icon="refresh"
          variant="secondary"
          outlined
          :loading="loading"
          @click="load"
        />
      </div>
      <p class="text-xs text-surface-500 dark:text-surface-400">
        <span class="font-medium">Pagina type:</span>
        kies <span class="font-medium">Standaard CORE-pagina</span> voor direct gebruik, of
        <span class="font-medium">Eigen klantpagina (override)</span> als je zelf
        <code class="text-xs px-1 rounded bg-surface-100 dark:bg-surface-800">resources/js/maestro/publicHome.vue</code>
        beheert.
      </p>
    </section>

    <section
      v-if="status"
      class="rounded-lg border border-surface-200 dark:border-surface-700 p-4 flex flex-col gap-4"
    >
      <div class="flex flex-wrap items-center justify-between gap-2">
        <div class="flex items-center gap-2">
          <h2 class="font-semibold text-surface-900 dark:text-surface-0">
            Status
          </h2>
          <BaseTag
            :severity="signalSeverity(status.status)"
            :value="signalLabel(status.status)"
            class="text-xs"
          />
        </div>
        <code class="text-xs px-2 py-1 rounded bg-surface-100 dark:bg-surface-800">
          Route: {{ status.route }}
        </code>
      </div>

      <p class="body-small text-surface-600 dark:text-surface-400">
        {{ status.status_detail }}
      </p>

      <div class="flex flex-col gap-3">
        <article
          v-for="check in status.checks"
          :key="check.id"
          class="rounded-md border border-surface-200 dark:border-surface-700 bg-surface-50/70 dark:bg-surface-900/40 p-3 flex flex-col gap-2"
        >
          <div class="flex flex-wrap items-center gap-2">
            <span class="font-medium text-surface-900 dark:text-surface-0">
              {{ check.label }}
            </span>
            <BaseTag
              :severity="signalSeverity(check.status)"
              :value="signalLabel(check.status)"
              class="text-xs"
            />
          </div>
          <p class="body-small text-surface-600 dark:text-surface-400">
            {{ check.detail }}
          </p>
          <div v-if="check.commands?.length" class="flex flex-col gap-2">
            <div
              v-for="command in check.commands"
              :key="command"
              class="flex items-start gap-2"
            >
              <code
                class="text-xs px-2 py-1.5 rounded bg-surface-100 dark:bg-surface-800 break-all flex-1"
              >
                {{ command }}
              </code>
              <BaseButton
                variant="secondary"
                icon="copy"
                text
                rounded
                size="small"
                :icon-only="true"
                aria-label="Kopieer commando"
                @click="copyText(command)"
              />
            </div>
          </div>
        </article>
      </div>
    </section>
  </div>
</template>
