<script setup lang="ts">
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref, watch, onBeforeUnmount } from "vue";
import "monaco-editor/min/vs/editor/editor.main.css";
// const store = commonStore();
const activeTab = ref<"details" | "Visualizations">("details");

const data = ref({
  params: {
    pageNum: 1,
    pageSize: 10,
    searchType: "",
    searchText: "",
  },
  results: [],
  totalDataLength: 0,
  pageLength: 0,
  modalMode: "",
  selectedData: null,
  allSelected: false,
  selected: [],
  isModalVisible: false,
  isConfirmDialogVisible: false,
  userOption: [],
});

const getCodeList = () => {
  // UserService.search(data.value.params).then((d) => {
  //   if (d.status === 200) {
  //     data.value.userOption = d.data.userList;
  //   }
  // });
};

const getData = () => {
  const params = { ...data.value.params };
  if (params.searchType === "" || params.searchText === "") {
    delete params.searchType;
    delete params.searchText;
  }
  data.value.results = [
    {
      name: "run-batch32-lr0.001",
      status: "Succeeded",
      Duration: "0:00:21",
      configProgress: "0/2",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-06-10T00:00:00Z",
    },
    {
      name: "run-batch64-lr0.001",
      status: "Failed",
      Duration: "0:00:21",
      configProgress: "1/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-06-09T00:00:00Z",
    },
    {
      name: "run-batch32-lr0.0005",
      status: "Succeeded",
      Duration: "0:00:21",
      configProgress: "0/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-06-01T00:00:00Z",
    },
    {
      name: "run-batch64-lr0.0005",
      status: "Running",
      Duration: "0:00:21",
      configProgress: "1/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-05-29T00:00:00Z",
    },
    {
      name: "run-augmented-data",
      status: "Succeeded",
      Duration: "0:00:21",
      configProgress: "0/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-05-31T00:00:00Z",
    },
  ];
  data.value.totalDataLength = 5;

  // DeviceService.search(params).then((d) => {
  //   if (d.status === 200) {
  //     data.value.results = d.data.deviceList;
  //     data.value.totalDataLength = d.data.totalCount;
  //     setTimeout(() => {
  //       setPaginationLength();
  //     }, 200);
  //   } else {
  //     store.setSnackbarMsg({
  //       text: "디바이스 조회 실패",
  //       color: "error",
  //     });
  //   }
  // });
  // DeviceService.search().then((d) => {
  //   data.value.totalDataLength = d.data.totalCount;
  //   setTimeout(() => {
  //     setPaginationLength();
  //   }, 200);
  // });
};

const activePlot = ref<"parallel" | "scatter" | "box" | "contour">("parallel");

// 공통 옵션 예시
const parameters = ["alpha", "l1_ratio", "max_depth", "n_estimators"];
const metrics = ["mae", "rmse", "r2", "accuracy"];

// 각 플롯별 선택값
const selectedParams = ref<string[]>([]);
const selectedX = ref("");
const selectedY = ref("");
const selectedZ = ref("");
const reverseColor = ref(false);

function clearAll() {
  selectedParams.value = [];
  selectedX.value = "";
  selectedY.value = "";
  selectedZ.value = "";
  reverseColor.value = false;
}
const runA = {
  id: "77578d20d81542f387149c1e3474f633",
  name: "defiant-horse-63",
  start: "2025-02-13 15:12",
  end: "2025-02-13 15:14",
  duration: "2.0s",
  params: { alpha: 0.2, l1_ratio: 0.2 },
  metrics: { mae: 0.564, r2: 0.237, rmse: 0.734 },
  tags: {
    estimator_class: "sklearn.pipeline.Pipeline",
    estimator_name: "Pipeline",
  },
  artifacts: ["estimator.html", "metrics.json"],
};
const runB = {
  id: "9a5da7476f0f4ad28117e0b2e8d58515",
  name: "magnificent-eel-8",
  start: "2025-02-13 15:12",
  end: "2025-02-13 15:13",
  duration: "1.9s",
  params: { alpha: 0.1, l1_ratio: 0.1 },
  metrics: { mae: 0.546, r2: 0.28, rmse: 0.713 },
  tags: {
    estimator_class: "sklearn.pipeline.Pipeline",
    estimator_name: "Pipeline",
  },
  artifacts: ["estimator.html", "metrics.json"],
};
// const setPaginationLength = () => {
//   if (data.value.totalDataLength % data.value.params.pageSize === 0) {
//     data.value.pageLength =
//       data.value.totalDataLength / data.value.params.pageSize;
//   } else {
//     data.value.pageLength = Math.ceil(
//       data.value.totalDataLength / data.value.params.pageSize,
//     );
//   }
// };

const saveData = (formData) => {
  if (data.value.modalMode === "create") {
    // DeviceService.add(formData).then((d) => {
    //   if (d.status === 200) {
    //     data.value.isModalVisible = false;
    //     store.setSnackbarMsg({
    //       text: "등록 되었습니다.",
    //       result: 200,
    //     });
    //     changePageNum(1);
    //   } else {
    //     store.setSnackbarMsg({
    //       text: d,
    //       result: 500,
    //     });
    //   }
    // });
  } else {
    // DeviceService.update(formData.deviceKey, formData).then((d) => {
    //   if (d.status === 200) {
    //     data.value.isModalVisible = false;
    //     store.setSnackbarMsg({
    //       text: "수정 되었습니다.",
    //       result: 200,
    //     });
    //     changePageNum();
    //   } else {
    //     store.setSnackbarMsg({
    //       text: d,
    //       result: 500,
    //     });
    //   }
    // });
  }
};

const removeData = (value) => {
  let removeList = value ? value : data.value.selected;
  const remove = (code) => {
    // return DeviceService.delete(code).then((d) => {
    //   if (d.status !== 200) {
    //     store.setSnackbarMsg({
    //       text: d,
    //       result: 500,
    //     });
    //   }
    // });
  };

  if (removeList.length === 1) {
    remove(removeList[0].deviceKey).then(() => {
      // store.setSnackbarMsg({
      //   text: "삭제되었습니다.",
      //   result: 200,
      // });
      changePageNum();
      data.value.isConfirmDialogVisible = false;
      data.value.selected = [];
      data.value.allSelected = false;
    });
  } else {
    Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
      () => {
        // store.setSnackbarMsg({
        //   text: "모두 삭제되었습니다.",
        //   result: 200,
        // });
        changePageNum();
        data.value.isConfirmDialogVisible = false;
        data.value.selected = [];
        data.value.allSelected = false;
      },
    );
  }
};

const changePageNum = (page) => {
  data.value.params.pageNum = page;
  getData();
};

const emit = defineEmits<{
  (e: "close"): void;
}>();

onMounted(() => {
  getData();
  getCodeList();
});
</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"
    >
      <!-- 1) Workflow Information -->
      <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>Compare Executions</div>
          </div>
        </v-card-item>
      </v-card>
      <v-tabs
        v-model="activeTab"
        background-color="grey lighten-4"
        style="max-width: 360px"
        grow
      >
        <v-tab value="details">Details</v-tab>
        <v-tab value="Visualizations">Visualizations</v-tab>
      </v-tabs>
      <div v-if="activeTab === 'details'" fluid flat>
        <v-card class="bordered-box mb-6 w-100 rounded-lg pa-8">
          <v-card-title class="grey lighten-4 py-2 px-4">
            <span class="font-weight-bold">Run Detail </span>
          </v-card-title>
          <v-card-text class="px-6 pb-6 pt-4">
            <!-- Workflow Name / Version -->
            <v-row align="center" class="py-2">
              <v-col cols="2" class="text-h6 font-weight-bold"> Run ID: </v-col>
              <v-col cols="5">{{ runA.id }}</v-col>
              <v-col cols="5">{{ runB.id }}</v-col>
              <v-col cols="2" class="text-h6 font-weight-bold">
                Run Name:
              </v-col>
              <v-col cols="5">{{ runA.name }}</v-col>
              <v-col cols="5">{{ runB.name }}</v-col>
              <v-col cols="2" class="text-h6 font-weight-bold">
                Start Name:
              </v-col>
              <v-col cols="5">{{ runA.start }}</v-col>
              <v-col cols="5">{{ runB.start }}</v-col>
              <v-col cols="2" class="text-h6 font-weight-bold">
                End Name:
              </v-col>
              <v-col cols="5">{{ runA.end }}</v-col>
              <v-col cols="5">{{ runB.end }}</v-col>
              <v-col cols="2" class="text-h6 font-weight-bold">
                Duration:
              </v-col>
              <v-col cols="5">{{ runA.duration }}</v-col>
              <v-col cols="5">{{ runB.duration }}</v-col>
            </v-row>
            <v-divider class="my-2" />
          </v-card-text>
          <v-card-title class="grey lighten-4 py-2 px-4">
            <span class="font-weight-bold">Parameters </span>
          </v-card-title>
          <v-card-text class="px-6 pb-6 pt-4">
            <!-- Workflow Name / Version -->
            <v-row align="center" class="py-2">
              <v-col cols="2" class="text-h6 font-weight-bold"> alpha </v-col>
              <v-col cols="5">{{ runA.params.alpha }}</v-col>
              <v-col cols="5">{{ runB.params.alpha }}</v-col>

              <v-col cols="2" class="text-h6 font-weight-bold">
                l1_ratio
              </v-col>
              <v-col cols="5">{{ runA.params.l1_ratio }}</v-col>
              <v-col cols="5">{{ runB.params.l1_ratio }}</v-col>
            </v-row>
            <v-divider class="my-2" />
          </v-card-text>
          <v-card-title class="grey lighten-4 py-2 px-4">
            <span class="font-weight-bold">Metrics</span>
          </v-card-title>
          <v-card-text class="px-6 pb-6 pt-4">
            <!-- Workflow Name / Version -->
            <v-row align="center" class="py-2">
              <v-col cols="2" class="text-h6 font-weight-bold"> mae </v-col>
              <v-col cols="5">{{ runA.metrics.mae }}</v-col>
              <v-col cols="5">{{ runA.metrics.mae }}</v-col>

              <v-col cols="2" class="text-h6 font-weight-bold"> r2 </v-col>
              <v-col cols="5">{{ runA.metrics.r2 }}</v-col>
              <v-col cols="5">{{ runA.metrics.r2 }}</v-col>
              <v-col cols="2" class="text-h6 font-weight-bold"> rmse </v-col>
              <v-col cols="5">{{ runA.metrics.rmse }}</v-col>
              <v-col cols="5">{{ runA.metrics.rmse }}</v-col>
            </v-row>
            <v-divider class="my-2" />
          </v-card-text>

          <v-card-title class="grey lighten-4 py-2 px-4">
            <span class="font-weight-bold">Tags </span>
          </v-card-title>
          <v-card-text class="px-6 pb-6 pt-4">
            <!-- Workflow Name / Version -->
            <v-row align="center" class="py-2">
              <v-col cols="2" class="text-h6 font-weight-bold">
                estimator_class
              </v-col>
              <v-col cols="5">{{ runA.tags.estimator_class }}</v-col>
              <v-col cols="5">{{ runA.tags.estimator_class }}</v-col>
              <v-col cols="2" class="text-h6 font-weight-bold">
                estimator_name
              </v-col>
              <v-col cols="5">{{ runA.tags.estimator_name }}</v-col>
              <v-col cols="5">{{ runA.tags.estimator_name }}</v-col>
            </v-row>
            <v-divider class="my-2" />
          </v-card-text>
          <v-card-title class="grey lighten-4 py-2 px-4">
            <span class="font-weight-bold">Artifacts</span>
          </v-card-title>
          <v-sheet class="d-flex justify-end mt-4">
            <v-btn color="primary" @click="emit('close')">Back to List</v-btn>
          </v-sheet>
        </v-card>
      </div>
      <div v-show="activeTab === 'Visualizations'">
        <!-- 2차 탭: 플롯 종류 -->
        <v-tabs
          v-model="activePlot"
          density="compact"
          background-color="transparent"
          class="sub-tabs mt-4"
          grow
          show-arrows
          slider-color="secondary"
        >
          <v-tab value="parallel">Parallel Coordinates Plot</v-tab>
          <v-tab value="scatter">Scatter Plot</v-tab>
          <v-tab value="box">Box Plot</v-tab>
          <v-tab value="contour">Contour Plot</v-tab>
        </v-tabs>

        <!-- 컨텐츠 카드 -->
        <v-card flat class="px-6" elevation="2">
          <v-row>
            <!-- 좌측 컨트롤 -->
            <v-col cols="12" md="4" class="pr-4 pt-8">
              <v-sheet class="pa-4" elevation="1" style="background: #1e1e1e">
                <div v-if="activePlot === 'parallel'">
                  <v-select
                    v-model="selectedParams"
                    :items="parameters"
                    label="Parameters"
                    multiple
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-select
                    v-model="selectedY"
                    :items="metrics"
                    label="Metrics"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-btn text @click="clearAll">Clear All</v-btn>
                </div>

                <div v-else-if="activePlot === 'scatter'">
                  <v-select
                    v-model="selectedX"
                    :items="parameters"
                    label="X-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-select
                    v-model="selectedY"
                    :items="metrics"
                    label="Y-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-btn text @click="clearAll">Clear All</v-btn>
                </div>

                <div v-else-if="activePlot === 'box'">
                  <v-select
                    v-model="selectedX"
                    :items="parameters"
                    label="X-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-select
                    v-model="selectedY"
                    :items="metrics"
                    label="Y-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-btn text @click="clearAll">Clear All</v-btn>
                </div>

                <div v-else-if="activePlot === 'contour'">
                  <v-select
                    v-model="selectedX"
                    :items="metrics"
                    label="X-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-select
                    v-model="selectedY"
                    :items="metrics"
                    label="Y-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-select
                    v-model="selectedZ"
                    :items="[
                      'training_score',
                      'validation_score',
                      'mae',
                      'rmse',
                    ]"
                    label="Z-axis"
                    dense
                    hide-details
                    class="mb-4"
                  />
                  <v-switch
                    v-model="reverseColor"
                    label="Reverse color"
                    dense
                    hide-details
                  />
                  <v-btn text @click="clearAll" class="mt-4">Clear All</v-btn>
                </div>
              </v-sheet>
            </v-col>

            <!-- 우측 그래프 placeholder -->
            <v-col cols="12" md="8">
              <v-sheet class="placeholder-box" height="400px" elevation="1" />
            </v-col>
          </v-row>
          <v-sheet class="d-flex justify-end my-4">
            <v-btn color="primary" @click="emit('close')">Back to List</v-btn>
          </v-sheet>
        </v-card>
      </div>
    </v-card>
  </v-container>
</template>

<style scoped>
.editor-container {
  width: 100%;
  height: 900px;
  max-height: 900px;
  border: 1px solid #444;
  border-radius: 4px;
}
</style>
