<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ExperimentService } from "@/components/service/management/ExperimentService";
import { ProjectService } from "@/components/service/project/projectService"; // ← 프로젝트 상세용

const props = defineProps<{ id: number | string }>();
const emit = defineEmits<{ (e: "close"): void }>();

const loading = ref(false);
const detailRaw = ref<any | null>(null);

const experimentInfo = ref({
  experimentName: "-",
  projectName: "-",
  createdDate: "-",
  createdId: "-",
  description: "-",
  kubeFlowId: "-",
  mlFlowId: "-",
});

const formatIso = (s?: string) =>
  s ? String(s).replace("T", " ").slice(0, 19) : "-";

const mapToViewModel = (raw: any) => ({
  experimentName: raw.displayName ?? raw.name ?? "-",
  projectName: "-",
  createdDate: formatIso(raw.lastUpdateTime),
  createdId: raw.regUserId ?? "-",
  description: raw.description ?? "-",
  kubeFlowId: raw.kubeFlowId ?? "-",
  mlFlowId: raw.mlFlowId ?? "-",
});

const info = computed(() => mapToViewModel(detailRaw.value || {}));

async function fetchProjectName(projectId?: number) {
  if (!projectId && projectId !== 0) return;
  try {
    const res = await ProjectService.fetchProjectById(projectId as number);
    const prj = res?.data ?? res;
    experimentInfo.value.projectName = prj?.prjNm ?? prj?.name ?? "-";
  } catch (e) {
    console.warn("[Experiment/View] project fetch fail:", e);
  }
}

async function fetchDetail(id: number | string) {
  const idNum = typeof id === "string" ? Number(id) : id;
  if (!Number.isFinite(idNum as number)) return;

  loading.value = true;
  try {
    const res = await ExperimentService.view(idNum as number);
    detailRaw.value = res?.data ?? res;

    const vm = mapToViewModel(detailRaw.value);
    experimentInfo.value = { ...experimentInfo.value, ...vm };

    // 프로젝트명 별도 조회
    await fetchProjectName(detailRaw.value?.projectId);
  } catch (e) {
    console.error("[Experiment/View] fetch detail error:", e);
  } finally {
    loading.value = false;
  }
}

onMounted(() => fetchDetail(props.id));
watch(
  () => props.id,
  (nv) => {
    if (nv !== undefined && nv !== null && nv !== "") fetchDetail(nv);
  },
);
</script>

<template>
  <v-container fluid class="h-100 pa-5 d-flex flex-column align-center">
    <v-card
      flat
      class="bg-shades-transparent d-flex flex-column justify-center w-100"
    >
      <v-card flat class="bg-shades-transparent w-100">
        <v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
          <div class="d-flex flex-row justify-start align-center">
            <div class="text-primary">View Details</div>
          </div>
        </v-card-item>
      </v-card>

      <v-card
        flat
        class="bordered-box mb-6 w-100 rounded-lg pa-8 position-relative"
      >
        <v-card-title class="grey lighten-4 py-2 px-4">
          <span class="font-weight-bold">Experiment Information</span>
        </v-card-title>

        <v-card-text class="px-6 pb-6 pt-4">
          <!-- Experiment Name -->
          <v-row align="center" class="py-2">
            <v-col cols="3" class="text-h6 font-weight-bold"
              >Experiment Name</v-col
            >
            <v-col cols="9" class="pa-2">{{
              experimentInfo.experimentName
            }}</v-col>
          </v-row>
          <VDivider class="my-2" />

          <!-- Project Name -->
          <v-row align="center" class="py-2">
            <v-col cols="3" class="text-h6 font-weight-bold"
              >Project Name</v-col
            >
            <v-col cols="9" class="pa-2">{{
              experimentInfo.projectName
            }}</v-col>
          </v-row>
          <VDivider class="my-2" />

          <!-- Created Date / ID -->
          <v-row align="center" class="py-2">
            <v-col cols="3" class="text-h6 font-weight-bold">Created ID</v-col>
            <v-col cols="3" class="pa-2">{{ experimentInfo.createdId }}</v-col>
            <v-col cols="3" class="text-h6 font-weight-bold"
              >Created Date</v-col
            >
            <v-col cols="3" class="pa-2">{{
              experimentInfo.createdDate
            }}</v-col>
          </v-row>
          <VDivider class="my-2" />

          <!-- Kubeflow / MLflow ID -->
          <v-row align="center" class="py-2">
            <v-col cols="3" class="text-h6 font-weight-bold">Kubeflow ID</v-col>
            <v-col cols="3" class="pa-2">{{ experimentInfo.kubeFlowId }}</v-col>
            <v-col cols="3" class="text-h6 font-weight-bold">MLflow ID</v-col>
            <v-col cols="3" class="pa-2">{{ experimentInfo.mlFlowId }}</v-col>
          </v-row>
          <VDivider class="my-2" />

          <!-- Description -->
          <v-row align="center" class="py-2">
            <v-col cols="3" class="text-h6 font-weight-bold">Description</v-col>
            <v-col cols="9" class="pa-2">{{
              experimentInfo.description
            }}</v-col>
          </v-row>
        </v-card-text>

        <v-overlay
          :model-value="loading"
          contained
          persistent
          class="align-center justify-center"
        >
          <v-progress-circular indeterminate size="48" />
        </v-overlay>

        <v-sheet class="d-flex justify-end mb-2">
          <v-btn color="primary" @click="emit('close')">Back to List</v-btn>
        </v-sheet>
      </v-card>
    </v-card>
  </v-container>
</template>
