<template>
  <LayoutComponent>
    <div class="admin-page-wrapper pa-4">
      <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>
        <v-btn color="secondary" variant="outlined" :loading="podLoading" @click="fetchPodStatus">
          <v-icon start>mdi-kubernetes</v-icon>
          Pod 상태 조회
        </v-btn>
        <span v-if="loading" class="text-body-2">조회 중…</span>
        <span v-if="podLoading" class="text-body-2">Pod 조회 중…</span>
      </div>
      <!-- 기존: HTTP 연결 확인 -->
      <v-row dense>
        <v-col cols="12" md="4">
          <v-card variant="outlined" class="pa-4">
            <v-card-title class="text-subtitle-1">KFP</v-card-title>
            <v-card-text>
              <v-chip v-if="status?.kfp" :color="status?.kfp?.status === 'ok' ? 'success' : 'grey'" size="small">{{ status?.kfp?.status === 'ok' ? '정상' : (status?.kfp?.status === 'error' ? '오류' : '미설정') }}</v-chip>
              <v-chip v-else color="grey" size="small">{{ loading ? '조회 중' : '미조회' }}</v-chip>
              <p class="text-caption mt-2">{{ status?.kfp?.message ?? (loading ? '연결 중...' : '위 [상태 조회] 버튼을 눌러 주세요.') }}</p>
            </v-card-text>
          </v-card>
        </v-col>
        <v-col cols="12" md="4">
          <v-card variant="outlined" class="pa-4">
            <v-card-title class="text-subtitle-1">MLflow</v-card-title>
            <v-card-text>
              <v-chip v-if="status?.mlflow" :color="status?.mlflow?.status === 'ok' ? 'success' : 'grey'" size="small">{{ status?.mlflow?.status === 'ok' ? '정상' : (status?.mlflow?.status === 'error' ? '오류' : '미설정') }}</v-chip>
              <v-chip v-else color="grey" size="small">{{ loading ? '조회 중' : '미조회' }}</v-chip>
              <p class="text-caption mt-2">{{ status?.mlflow?.message ?? (loading ? '연결 중...' : '위 [상태 조회] 버튼을 눌러 주세요.') }}</p>
            </v-card-text>
          </v-card>
        </v-col>
        <v-col cols="12" md="4">
          <v-card variant="outlined" class="pa-4">
            <v-card-title class="text-subtitle-1">MinIO</v-card-title>
            <v-card-text>
              <v-chip v-if="status?.minio" :color="status?.minio?.status === 'ok' ? 'success' : 'grey'" size="small">{{ status?.minio?.status === 'ok' ? '정상' : (status?.minio?.status === 'error' ? '오류' : '미설정') }}</v-chip>
              <v-chip v-else color="grey" size="small">{{ loading ? '조회 중' : '미조회' }}</v-chip>
              <p class="text-caption mt-2">{{ status?.minio?.message ?? (loading ? '연결 중...' : '위 [상태 조회] 버튼을 눌러 주세요.') }}</p>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- 신규: Pod 상태 (K8s) -->
      <p class="text-body-2 text-medium-emphasis mt-4 mb-2">Kubernetes Pod 상태</p>
      <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 justify-space-between">
              KFP Pod
              <v-btn size="small" variant="tonal" @click="openDetail('kfp')">상세</v-btn>
            </v-card-title>
            <v-card-text>
              <template v-if="podStatus('kfp')">
                <v-chip :color="podStatus('kfp')?.ok ? 'success' : 'warning'" size="small">
                  {{ podStatus('kfp')?.running }}/{{ podStatus('kfp')?.total }} Running
                </v-chip>
                <p class="text-caption mt-2">{{ podStatus('kfp')?.message }}</p>
              </template>
              <template v-else>
                <v-chip color="grey" size="small">{{ podLoading ? '조회 중' : '미조회' }}</v-chip>
                <p class="text-caption mt-2">{{ podStatusHint('kfp') }}</p>
              </template>
            </v-card-text>
          </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 justify-space-between">
              MLflow Pod
              <v-btn size="small" variant="tonal" @click="openDetail('mlflow')">상세</v-btn>
            </v-card-title>
            <v-card-text>
              <template v-if="podStatus('mlflow')">
                <v-chip :color="podStatus('mlflow')?.ok ? 'success' : 'warning'" size="small">
                  {{ podStatus('mlflow')?.running }}/{{ podStatus('mlflow')?.total }} Running
                </v-chip>
                <p class="text-caption mt-2">{{ podStatus('mlflow')?.message }}</p>
              </template>
              <template v-else>
                <v-chip color="grey" size="small">{{ podLoading ? '조회 중' : '미조회' }}</v-chip>
                <p class="text-caption mt-2">{{ podStatusHint('mlflow') }}</p>
              </template>
            </v-card-text>
          </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 justify-space-between">
              MinIO Pod
              <v-btn size="small" variant="tonal" @click="openDetail('minio')">상세</v-btn>
            </v-card-title>
            <v-card-text>
              <template v-if="podStatus('minio')">
                <v-chip :color="podStatus('minio')?.ok ? 'success' : 'warning'" size="small">
                  {{ podStatus('minio')?.running }}/{{ podStatus('minio')?.total }} Running
                </v-chip>
                <p class="text-caption mt-2">{{ podStatus('minio')?.message }}</p>
              </template>
              <template v-else>
                <v-chip color="grey" size="small">{{ podLoading ? '조회 중' : '미조회' }}</v-chip>
                <p class="text-caption mt-2">{{ podStatusHint('minio') }}</p>
              </template>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <p v-if="status?.updatedAt" class="text-caption text-grey mt-2">연결 마지막 갱신: {{ status.updatedAt }}</p>
      <p v-if="podStatusData?.updatedAt" class="text-caption text-grey">Pod 마지막 갱신: {{ podStatusData.updatedAt }}</p>

      <v-dialog v-model="detailDialog" max-width="min(96vw, 1100px)" persistent scrollable>
        <v-card>
          <v-card-title class="d-flex align-center">
            {{ detailService === 'kfp' ? 'KFP' : detailService === 'mlflow' ? 'MLflow' : 'MinIO' }} Pod 상세
            <v-spacer />
            <v-btn
              v-if="detailPods.length > 0"
              color="primary"
              variant="tonal"
              size="small"
              class="mr-2"
              :loading="logLoading"
              @click="loadAllPodLogs"
            >
              전체 로그
            </v-btn>
            <v-btn icon variant="text" @click="detailDialog = false"><v-icon>mdi-close</v-icon></v-btn>
          </v-card-title>
          <v-card-text>
            <p v-if="detailPods.length === 0" class="text-caption text-medium-emphasis">Pod가 없습니다.</p>
            <div v-else class="mb-3">
              <p class="text-caption text-medium-emphasis mb-2">아래 Pod들의 로그를 [전체 로그]로 한 번에 볼 수 있습니다.</p>
              <div v-for="p in detailPods" :key="p.name" class="d-flex align-center mb-1">
                <span class="text-body-2 mr-2">{{ p.name }}</span>
                <v-chip size="small" :color="p.phase === 'Running' ? 'success' : 'grey'">{{ p.phase ?? '-' }}</v-chip>
              </div>
            </div>
            <div v-if="logContent" class="mt-2">
              <p class="text-caption text-medium-emphasis mb-1">통합 로그 (Pod 순서대로, 전체 줄 수)</p>
              <pre class="log-viewer log-viewer--wide">{{ logContent }}</pre>
            </div>
          </v-card-text>
        </v-card>
      </v-dialog>
    </div>
  </LayoutComponent>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import LayoutComponent from "@/components/common/LayoutComponent.vue";
import { AdminService } from "@/components/service/management/adminService";
import type { PodStatus, PodStatusItem } from "@/components/service/management/adminService";
import { commonStore } from "@/stores/commonStore";

const loading = ref(false);
const status = ref<any>(null);
const podLoading = ref(false);
const podStatusData = ref<any>(null);
const store = commonStore();

const detailDialog = ref(false);
const detailService = ref<"kfp" | "mlflow" | "minio" | null>(null);
const logContent = ref("");
const logLoading = ref(false);

const detailPods = computed((): PodStatusItem[] => {
  if (!detailService.value || !podStatusData.value) return [];
  const ps = podStatusData.value[detailService.value] as PodStatus | undefined;
  return ps?.pods ?? [];
});

function podStatus(service: "kfp" | "mlflow" | "minio"): PodStatus | undefined {
  return podStatusData.value?.[service];
}

function podStatusHint(service: "kfp" | "mlflow" | "minio"): string {
  if (podLoading.value) return "...";
  if (!podStatusData.value) return "위 [Pod 상태 조회] 버튼을 눌러 주세요.";
  const msg = podStatusData.value?.message;
  if (msg) return msg;
  return "Pod 정보 없음 (label-selector 확인)";
}

function openDetail(service: "kfp" | "mlflow" | "minio") {
  detailService.value = service;
  logContent.value = "";
  detailDialog.value = true;
}

async function loadAllPodLogs() {
  const ns = podStatusData.value?.namespace ?? "kubeflow";
  const names = detailPods.value.map((p) => p.name).filter(Boolean) as string[];
  if (names.length === 0) return;
  logLoading.value = true;
  logContent.value = "전체 Pod 로그 불러오는 중…";
  try {
    const res = await AdminService.getPodLogsAggregate(ns, names, 0);
    logContent.value = (res as any)?.data ?? res ?? "로그를 불러올 수 없습니다.";
  } catch {
    logContent.value = "로그 조회 실패";
    store.setSnackbarMsg({ text: "Pod 통합 로그 조회 실패", color: "error", result: 500 });
  } finally {
    logLoading.value = false;
  }
}

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

async function fetchPodStatus() {
  podLoading.value = true;
  try {
    const res = await AdminService.getPodStatus();
    podStatusData.value = (res as any)?.data ?? res ?? null;
    if (podStatusData.value?.message) {
      store.setSnackbarMsg({ text: podStatusData.value.message, color: "warning", result: 200 });
    }
  } catch {
    podStatusData.value = null;
    store.setSnackbarMsg({ text: "Pod 상태 조회 실패", color: "error", result: 500 });
  } finally {
    podLoading.value = false;
  }
}
</script>

<style scoped>
.admin-page-wrapper {
  width: 100%;
  min-height: 40vh;
}
.log-viewer--wide {
  max-height: min(70vh, 800px);
}
.log-viewer {
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 12px;
  border-radius: 4px;
  max-height: 400px;
  overflow: auto;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
