<template>
  <section class="page">
    <GnPageHeader title="Scopes" kicker="Scripts">
      <template #actions>
        <GnBadge variant="primary">{{ scriptsStore.totalScopes }} scopes</GnBadge>
      </template>
    </GnPageHeader>

    <AppLoadingState v-if="scriptsStore.isLoadingScopes" text="Loading scopes" />

    <AppErrorState
      v-else-if="scriptsStore.errorScopes"
      title="Scopes loading failed"
      :error="scriptsStore.errorScopes"
      :retry="scriptsStore.loadScopes"
    />

    <AppEmptyState
      v-else-if="scriptsStore.scopes.length === 0"
      title="No scopes"
      message="No script scopes registered."
    />

    <div v-else class="devices-panel">
      <GnTable :columns="tableColumns" :rows="scriptsStore.scopes" caption="Script scopes">
        <template #cell-name="{ row }">
          <router-link
            :to="{ name: 'script-detail', params: { type: 'scopes', id: row.name } }"
            class="script-link"
          >
            {{ row.name }}
          </router-link>
        </template>

        <template #cell-state="{ row }">
          <GnBadge :variant="row.state === 'enabled' ? 'success' : 'secondary'"
          >{{ row.state }}</GnBadge>
        </template>

        <template #cell-actions="{ row }">
          <GnButton
            v-if="row.state === 'enabled' && perm.has('scripts.edit')"
            variant="secondary"
            icon="ph-pause"
            @click="toggle(row.name, false)"
          >
            Disable
          </GnButton>
          <GnButton
            v-else-if="perm.has('scripts.edit')"
            variant="primary"
            icon="ph-play"
            @click="toggle(row.name, true)"
          >
            Enable
          </GnButton>
        </template>
      </GnTable>
    </div>
  </section>
</template>

<script setup>
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { useScriptsStore } from "../../../stores/scripts";
import { usePermission } from "../../../composables/usePermission.js";
import { GnPageHeader, GnBadge, GnTable, GnButton } from "gnexus-ui-kit/vue";
import AppEmptyState from "../../../components/feedback/AppEmptyState.vue";
import AppErrorState from "../../../components/feedback/AppErrorState.vue";
import AppLoadingState from "../../../components/feedback/AppLoadingState.vue";

const router = useRouter();
const scriptsStore = useScriptsStore();
const perm = usePermission();

const tableColumns = [
  { key: "name", label: "Name" },
  { key: "filename", label: "File" },
  { key: "state", label: "State" },
  { key: "path", label: "Path" },
  { key: "actions", label: "Actions" },
];

function goToDetail(name) {
  router.push({ name: "script-detail", params: { type: "scopes", id: name } });
}

function toggle(name, enabled) {
  scriptsStore.setScopeState(name, enabled);
}

onMounted(() => {
  scriptsStore.loadScopes();
});
</script>

<style scoped>
.script-link {
  color: var(--color-primary);
}
</style>
