<script setup lang="ts">
import { ref, onBeforeUnmount } from "vue";
import AdminService, {
  type AdminStatusResponse,
  type ComponentStatus,
} from "@/components/service/management/adminService";
import { commonStore } from "@/stores/commonStore";

const POLL_INTERVAL_MS = 30_000;

const status = ref<AdminStatusResponse | null>(null);
const loading = ref(false);
const restarting = ref<string | null>(null);
let pollTimer: ReturnType<typeof setInterval> | null = null;
const store = commonStore();

function statusLabel(s: ComponentStatus): string {
  if (s.status === "ok") return "정상";
  if (s.status === "error") return "오류";
  return "미설정";
}

function statusColor(s: ComponentStatus): string {
  if (s.status === "ok") return "success";
  if (s.status === "error") return "error";
  return "grey";
}

async function fetchStatus() {
  loading.value = true;
  try {
    const res = await AdminService.getStatus();
    status.value = (res as any).data ?? res;
    startPollIfNeeded();
  } catch (e) {
    status.value = null;
    store.setSnackbarMsg({
      text: "상태 조회 실패",
      color: "error",
      result: 500,
    });
  } finally {
    loading.value = false;
  }
}

async function doRestart(service: string) {
  restarting.value = service;
  try {
    const res = await AdminService.restart(service);
    const body = (res as any).data ?? res;
    store.setSnackbarMsg({
      text: body?.message ?? (body?.success ? "요청 접수됨" : "실패"),
      color: body?.success ? "success" : "warning",
      result: body?.success ? 200 : 400,
    });
    if (body?.success) await fetchStatus();
  } catch (e) {
    store.setSnackbarMsg({
      text: "재시작 요청 실패",
      color: "error",
      result: 500,
    });
  } finally {
    restarting.value = null;
  }
}

/** 조회 성공 후 30초마다 자동 갱신 */
function startPollIfNeeded() {
  if (!pollTimer) {
    pollTimer = setInterval(fetchStatus, POLL_INTERVAL_MS);
  }
}

onBeforeUnmount(() => {
  if (pollTimer) clearInterval(pollTimer);
});
</script>

<template>
  <div class="admin-page">
    <v-container fluid class="pa-6">
      <h1 class="text-h4 mb-4">관리자 · 시스템 상태</h1>
      <p class="text-body-2 text-medium-emphasis mb-4">
        KFP, MLflow, MinIO 헬스 상태. 아래 버튼으로 조회 후 30초마다 자동 갱신됩니다.
      </p>

      <div class="d-flex align-center mb-4 flex-wrap gap-2">
        <v-btn
          color="primary"
          :loading="loading"
          @click="fetchStatus()"
        >
          <v-icon start>mdi-refresh</v-icon>
          상태 조회
        </v-btn>
        <span v-if="loading" class="text-body-2 text-medium-emphasis">조회 중…</span>
      </div>

      <v-row dense>
        <v-col cols="12" md="4">
          <v-card variant="outlined" class="pa-4">
            <v-card-title class="text-subtitle-1 d-flex align-center">
              <v-icon start>mdi-api</v-icon>
              KFP
            </v-card-title>
            <v-card-text>
              <v-chip
                v-if="status?.kfp"
                :color="statusColor(status.kfp)"
                size="small"
                class="mb-2"
              >
                {{ statusLabel(status.kfp) }}
              </v-chip>
              <v-chip v-else color="grey" size="small" class="mb-2">{{ loading ? "조회 중" : "미조회" }}</v-chip>
              <p class="text-caption text-medium-emphasis mb-0">
                {{ status?.kfp?.message ?? (loading ? "연결 중..." : "위 [상태 조회] 버튼을 눌러 주세요.") }}
              </p>
            </v-card-text>
            <v-card-actions>
              <v-btn
                size="small"
                variant="outlined"
                :loading="restarting === 'kfp'"
                :disabled="!status?.kfp || status.kfp.status === 'skip'"
                @click="doRestart('kfp')"
              >
                재시작 요청
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-col>
        <v-col cols="12" md="4">
          <v-card variant="outlined" class="pa-4">
            <v-card-title class="text-subtitle-1 d-flex align-center">
              <v-icon start>mdi-chart-line</v-icon>
              MLflow
            </v-card-title>
            <v-card-text>
              <v-chip
                v-if="status?.mlflow"
                :color="statusColor(status.mlflow)"
                size="small"
                class="mb-2"
              >
                {{ statusLabel(status.mlflow) }}
              </v-chip>
              <v-chip v-else color="grey" size="small" class="mb-2">{{ loading ? "조회 중" : "미조회" }}</v-chip>
              <p class="text-caption text-medium-emphasis mb-0">
                {{ status?.mlflow?.message ?? (loading ? "연결 중..." : "위 [상태 조회] 버튼을 눌러 주세요.") }}
              </p>
            </v-card-text>
            <v-card-actions>
              <v-btn
                size="small"
                variant="outlined"
                :loading="restarting === 'mlflow'"
                :disabled="!status?.mlflow || status.mlflow.status === 'skip'"
                @click="doRestart('mlflow')"
              >
                재시작 요청
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-col>
        <v-col cols="12" md="4">
          <v-card variant="outlined" class="pa-4">
            <v-card-title class="text-subtitle-1 d-flex align-center">
              <v-icon start>mdi-database</v-icon>
              MinIO
            </v-card-title>
            <v-card-text>
              <v-chip
                v-if="status?.minio"
                :color="statusColor(status.minio)"
                size="small"
                class="mb-2"
              >
                {{ statusLabel(status.minio) }}
              </v-chip>
              <v-chip v-else color="grey" size="small" class="mb-2">{{ loading ? "조회 중" : "미조회" }}</v-chip>
              <p class="text-caption text-medium-emphasis mb-0">
                {{ status?.minio?.message ?? (loading ? "연결 중..." : "위 [상태 조회] 버튼을 눌러 주세요.") }}
              </p>
            </v-card-text>
            <v-card-actions>
              <v-btn
                size="small"
                variant="outlined"
                :loading="restarting === 'minio'"
                :disabled="!status?.minio || status.minio.status === 'skip'"
                @click="doRestart('minio')"
              >
                재시작 요청
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-col>
      </v-row>

      <p v-if="status?.updatedAt" class="text-caption text-grey mt-4">
        마지막 갱신: {{ status.updatedAt }}
      </p>
      <p v-else class="text-caption text-grey mt-4">
        위 [상태 조회] 버튼을 누르면 KFP, MLflow, MinIO 상태를 조회합니다.
      </p>
    </v-container>
  </div>
</template>

<style scoped lang="sass">
.admin-page
  min-height: 40vh
  width: 100%
</style>
