<script setup lang="ts">
import { trimTrailingSlashes, validateGatewayUrl } from "@corvus/shared";
import { onUnmounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { AdminSchedulerStatusView } from "@/types/admin-config";

const props = defineProps<{
  gatewayUrl: string;
  bearerToken: string;
}>();

const { t } = useI18n();

const scheduler = ref<AdminSchedulerStatusView | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);

let abortController: AbortController | undefined;
let fetchId = 0;

async function fetchSchedulerStatus(signal?: AbortSignal) {
  const myId = ++fetchId;
  loading.value = true;
  error.value = null;
  try {
    const base = validateGatewayUrl(props.gatewayUrl);
    if (!base) {
      scheduler.value = null;
      error.value = t("errors.invalidGatewayUrl");
      return;
    }
    const baseStr = trimTrailingSlashes(base.toString());
    const requestUrl = new URL("web/admin/scheduler", `${baseStr}/`);
    const res = await fetch(requestUrl.toString(), {
      headers: { Authorization: `Bearer ${props.bearerToken}` },
      signal,
    });
    if (!res.ok) {
      throw new Error(`HTTP ${res.status}`);
    }
    const data = await res.json();
    scheduler.value = data.scheduler ?? null;
  } catch (e: unknown) {
    if (e instanceof DOMException && e.name === "AbortError") return;
    error.value = e instanceof Error ? e.message : String(e);
  } finally {
    if (myId === fetchId) {
      loading.value = false;
    }
  }
}

watch(
  () => [props.gatewayUrl, props.bearerToken],
  () => {
    if (abortController) {
      abortController.abort();
    }
    abortController = new AbortController();
    fetchSchedulerStatus(abortController.signal);
  },
  { immediate: true }
);
onUnmounted(() => {
  abortController?.abort();
});
</script>

<template>
  <section class="card">
    <h2>{{ t("sections.schedulerStatus") }}</h2>
    <p v-if="loading" class="helper" aria-live="polite">{{ t("scheduler.loading") }}</p>
    <p v-else-if="error" class="error" aria-live="assertive">{{ error }}</p>
    <div v-else-if="scheduler" class="status-grid" data-testid="scheduler-status">
      <div class="status-item">
        <span class="status-label">{{ t("scheduler.enabled") }}</span>
        <span
          class="status-indicator"
          :class="scheduler.enabled ? 'configured' : 'not-configured'"
          aria-hidden="true"
        />
        <span class="status-value">{{
          scheduler.enabled ? t("scheduler.yes") : t("scheduler.no")
        }}</span>
      </div>
      <div class="status-item">
        <span class="status-label">{{ t("scheduler.maxTasks") }}</span>
        <span class="status-value">{{ scheduler.max_tasks }}</span>
      </div>
      <div class="status-item">
        <span class="status-label">{{ t("scheduler.maxConcurrent") }}</span>
        <span class="status-value">{{ scheduler.max_concurrent }}</span>
      </div>
      <div class="status-item">
        <span class="status-label">{{ t("scheduler.taskCount") }}</span>
        <span class="status-value">{{ scheduler.task_count }}</span>
      </div>
    </div>
  </section>
</template>

<style scoped>
.status-grid {
  display: grid;
  gap: 8px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border: 1px solid var(--corvus-color-border-default);
  border-radius: var(--corvus-radius-input);
  background: var(--corvus-color-bg-surface);
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  flex-shrink: 0;
}

.configured {
  background: var(--corvus-color-status-success);
}

.not-configured {
  background: var(--corvus-color-text-disabled);
}

.status-label {
  font-weight: 500;
  flex: 1;
}

.status-value {
  font-size: 12px;
  color: var(--corvus-color-text-secondary);
}
</style>
