<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import tz from "dayjs/plugin/timezone";

import IconDownloadBtn from "@/components/atoms/button/IconDownloadBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import CompareComponent from "@/components/templates/run/executions/CompareComponent.vue";
import ViewComponent from "@/components/templates/run/executions/ViewComponent.vue";
import ExecutionBaseDialog from "@/components/atoms/organisms/ExecutionBaseDialog.vue";

import { ExecutionsService } from "@/components/service/management/ExecutionsService";
import type { RunsSearchParams } from "@/components/models/management/Exeucutios";

dayjs.extend(utc);
dayjs.extend(tz);

const KST = "Asia/Seoul";

/* ===== UI 상태 ===== */
const openCompare = ref(false);
const openView = ref(false);

const tableHeader = [
  { label: "No", width: "5%", style: "word-break: keep-all;" },
  { label: "Execution Name", width: "20%", style: "word-break: keep-all;" },
  { label: "Status", width: "10%", style: "word-break: keep-all;" },
  { label: "Duration", width: "10%", style: "word-break: keep-all;" },
  { label: "Experiment", width: "15%", style: "word-break: keep-all;" },
  { label: "Workflow", width: "15%", style: "word-break: keep-all;" },
  { label: "Start Time", width: "15%", style: "word-break: keep-all;" },
  { label: "Registry Status", width: "10%", style: "word-break: keep-all;" },
  { label: "Action", width: "5%", style: "word-break: keep-all;" },
];

const searchOptions = [
  { searchType: "All", searchText: "" },
  { searchType: "Execution Name", searchText: "name" },
  { searchType: "Status", searchText: "status" },
  { searchType: "Duration", searchText: "duration" },
  { searchType: "Experiment", searchText: "experiment" },
  { searchType: "Workflow", searchText: "workflow" },
  { searchType: "Registry Status", searchText: "registryStatus" },
];

const execDialogOpen = ref(false);
const execMode = ref<"create" | "edit" | "clone">("create");
const execSelected = ref<any>(null);
const searchExperimentOptions = [{ searchType: "Experiment", searchText: "" }];
const searchWorkflowOptions = [{ searchType: "Workflow", searchText: "" }];
const workflowList = ref(["pipeline-a", "pipeline-b", "pipeline-c"]);
const executionTypes = ref(["One-off", "Recurring"]);

const pageSizeOptions = [
  { text: "10 페이지", value: 10 },
  { text: "50 페이지", value: 50 },
  { text: "100 페이지", value: 100 },
];

type UiRow = {
  no: number;
  name: string;
  status: string;
  duration: string;
  experiment: string;
  workflow: string;
  startTime: string;
  registryStatus: string;
  deviceKey: string; // run_id
};

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

/* ===== page_token 기반 페이지네이션 캐시 ===== */
const pageTokens = ref<string[]>([""]); // index=0은 첫 페이지(빈 토큰)
const nextPageToken = ref<string | undefined>();

/* ===== 헬퍼 ===== */
const mapState = (s?: string) => {
  switch ((s || "").toUpperCase()) {
    case "SUCCEEDED":
      return "Succeeded";
    case "FAILED":
      return "Failed";
    case "RUNNING":
      return "Running";
    case "PENDING":
      return "Pending";
    default:
      return s || "";
  }
};

const formatRegistry = (v?: string) => {
  const s = (v || "").toUpperCase();
  if (s === "AVAILABLE") return "Registered";
  if (s === "ARCHIVED") return "Archived";
  return v || "";
};
const kst = (v?: string | number | Date) =>
  v ? dayjs(v).tz(KST).format("YYYY-MM-DD HH:mm:ss") : "";
const duration = (start?: string, end?: string) => {
  if (!start) return "";
  const s = dayjs(start);
  const e = end ? dayjs(end) : dayjs();
  const diff = dayjs.duration(e.diff(s));
  const h = Math.floor(diff.asHours());
  const m = String(diff.minutes()).padStart(2, "0");
  const sec = String(diff.seconds()).padStart(2, "0");
  return `${h}:${m}:${sec}`;
};
const toRow = (run: any, no: number): UiRow => ({
  no,
  name: run?.display_name ?? run?.name ?? run?.run_id ?? "-",
  status: mapState(run?.state),
  duration: duration(run?.created_at, run?.finished_at),
  experiment: run?.experiment_id ?? "",
  workflow:
    run?.pipeline_version_reference?.pipeline_id ??
    run?.pipeline_version_reference?.pipeline_version_id ??
    "",
  startTime: kst(run?.created_at),
  registryStatus: formatRegistry(run?.storage_state),
  deviceKey: run?.run_id,
});

/* ===== 모든 페이지 콘솔 덤프 + 첫 페이지(최대 1000건) 테이블 반영 ===== */
const dumpAllRunsToConsole = async () => {
  let token: string | undefined = undefined;
  let page = 1;
  const pageSize = 10;

  const all: any[] = [];
  let totalSizeFromServer: number | undefined;

  do {
    const payload: RunsSearchParams = {
      page_token: token,
      page_size: pageSize,
      sort_by: "created_at_desc",
    };

    const res = await ExecutionsService.search(payload);
    const body = res?.data ?? {};
    const runs: any[] = Array.isArray(body.runs) ? body.runs : [];
    const next = body.next_page_token as string | undefined;

    if (page === 1) {
      totalSizeFromServer =
        Number(body.total_size ?? runs.length) || runs.length;
      console.log(`[Runs] total_size (server): ${totalSizeFromServer}`);
    }

    console.log(
      `[Runs] page ${page} — count: ${runs.length}, next_page_token: ${
        next ? "YES" : "NO"
      }`,
    );
    console.table(
      runs.map((r: any, i: number) => ({
        i,
        run_id: r.run_id,
        name: r.display_name ?? r.name,
        state: r.state,
        created_at: r.created_at,
        finished_at: r.finished_at,
      })),
    );

    all.push(...runs);
    token = next;
    page += 1;
  } while (token);

  console.log(`[Runs] aggregated count (fetched): ${all.length}`);
  if (typeof totalSizeFromServer === "number") {
    console.log(
      `[Runs] server total_size vs fetched: ${totalSizeFromServer} vs ${all.length}`,
    );
  }

  // 테이블에는 첫 페이지(최대 1000건)만 표시
  const firstPage = all.slice(0, pageSize);
  const firstNoStart = totalSizeFromServer ?? all.length;
  data.value.results = firstPage.map((r, i) => toRow(r, firstNoStart - i));
  data.value.totalDataLength = totalSizeFromServer ?? all.length;
  data.value.pageLength = Math.max(
    1,
    Math.ceil((totalSizeFromServer ?? all.length) / pageSize),
  );

  // 페이지 토큰 상태도 정리(첫 페이지만 의미 있게 유지)
  pageTokens.value = [""];
  nextPageToken.value = undefined;
};

/* ===== (옵션) 단일 페이지 가져오기 — 테이블 재조회 필요 시 사용 ===== */
const fetchPage = async (pageIndex: number) => {
  const token = pageTokens.value[pageIndex - 1] || undefined;

  const payload: RunsSearchParams = {
    page_token: token,
    page_size: data.value.params.pageSize, // 1000 고정
    sort_by: "created_at_desc",
  };

  const res = await ExecutionsService.search(payload);
  const body = res?.data ?? {};
  const runs: any[] = Array.isArray(body.runs) ? body.runs : [];
  const total = Number(body.total_size ?? runs.length) || runs.length;

  console.log(
    `[Runs] total_size: ${total}, pageIndex: ${pageIndex}, page_size: ${data.value.params.pageSize}, this_page: ${runs.length}, next_page_token:`,
    body.next_page_token || "(none)",
  );
  console.table(
    runs.map((r, i) => ({
      i,
      run_id: r.run_id,
      name: r.display_name ?? r.name,
      state: r.state,
      created_at: r.created_at,
      finished_at: r.finished_at,
    })),
  );

  const pageOffset = (pageIndex - 1) * data.value.params.pageSize;
  const firstNo = Math.max(total - pageOffset, 1);

  data.value.results = runs.map((r, i) => toRow(r, firstNo - i));
  data.value.totalDataLength = total;
  data.value.pageLength = Math.max(
    1,
    Math.ceil(total / data.value.params.pageSize),
  );

  nextPageToken.value = body.next_page_token;
  if (nextPageToken.value && !pageTokens.value[pageIndex]) {
    pageTokens.value[pageIndex] = nextPageToken.value;
  }
};

/* ===== 템플릿 이벤트에 맞춘 함수들 ===== */
const getData = async (newPage?: number) => {
  if (typeof newPage === "number") data.value.params.pageNum = newPage;

  // page_size 1000 고정이므로 기본은 1페이지만 사용
  await fetchPage(1);
};

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

const openCreateExecution = () => {
  execMode.value = "create";
  execSelected.value = null;
  execDialogOpen.value = true;
};
const openComparePage = () => {
  openCompare.value = true;
  openView.value = false;
};
const openInfoModal = () => {
  openView.value = true;
  openCompare.value = false;
};
const openModifyModal = () => {
  execMode.value = "edit";
  execDialogOpen.value = true;
};
const openDownloadModal = () => {
  data.value.selectedData = null;
  data.value.modalMode = "download";
};

const handleTerminate = () => alert("Terminate 작업 진행중...");
const handleRetry = () => alert("Retry 작업 진행중...");
const handleClone = () => alert("Clone 작업 진행중...");

const getSelectedAllData = () => {
  data.value.selected = data.value.allSelected
    ? data.value.results.map((x) => ({ deviceKey: x.deviceKey }))
    : [];
};

// 사용자가 드롭다운을 만지더라도 1000 고정을 유지하도록 강제
watch(
  () => data.value.params.pageSize,
  async (v) => {
    if (v !== 1000) data.value.params.pageSize = 1000;
    pageTokens.value = [""];
    nextPageToken.value = undefined;
    await getData(1);
  },
);

/* 초기 로드 */
onMounted(async () => {
  // 1) 전체 페이지 콘솔 덤프
  await dumpAllRunsToConsole();
  // 2) (선택) 테이블 새로고침이 필요하면 getData(1) 호출
  // await getData(1);
});
</script>

<template>
  <div class="w-100" v-if="!openCompare && !openView">
    <!-- <v-dialog v-model="data.isModalVisible" max-width="600" persistent>
    <FormComponent
      :edit-data="data.selectedData"
      :mode="data.modalMode"
      @close-modal="closeModal"
      @handle-data="saveData"
      :user-option="data.userOption"
    />
  </v-dialog>
  <v-dialog v-model="data.isConfirmDialogVisible" persistent max-width="300">
    <ConfirmDialogComponent
      @cancel="data.isConfirmDialogVisible = false"
      @delete="removeData(undefined)"
      @init="((data.selected = []), (data.allSelected = false))"
    />
  </v-dialog> -->
    <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 align-center 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">Executions</div>
            </div>
          </v-card-item>
        </v-card>
        <v-card flat class="bg-shades-transparent w-100">
          <v-card flat class="bg-shades-transparent mb-4">
            <div class="d-flex justify-center flex-wrap align-center">
              <v-responsive
                max-width="180"
                min-width="180"
                class="mr-3 mt-3 mb-3"
              >
                <v-select
                  v-model="data.params.searchType"
                  label="검색조건"
                  density="compact"
                  :items="searchOptions"
                  item-title="searchType"
                  item-value="searchText"
                  hide-details
                ></v-select>
              </v-responsive>
              <v-responsive
                max-width="180"
                min-width="180"
                class="mr-3 mt-3 mb-3"
              >
                <v-select
                  v-model="data.params.searchType"
                  label="검색조건"
                  density="compact"
                  :items="searchExperimentOptions"
                  item-title="searchType"
                  item-value="searchText"
                  hide-details
                ></v-select>
              </v-responsive>
              <v-responsive
                max-width="180"
                min-width="180"
                class="mr-3 mt-3 mb-3"
              >
                <v-select
                  v-model="data.params.searchType"
                  label="검색조건"
                  density="compact"
                  :items="searchWorkflowOptions"
                  item-title="searchType"
                  item-value="searchText"
                  hide-details
                ></v-select>
              </v-responsive>
              <v-responsive min-width="540" max-width="540">
                <v-text-field
                  v-model="data.params.searchText"
                  label="검색어"
                  density="compact"
                  clearable
                  required
                  class="mt-3 mb-3"
                  hide-details
                  @keyup.enter="changePageNum(1)"
                ></v-text-field>
              </v-responsive>

              <div class="ml-3">
                <v-btn
                  size="large"
                  color="primary"
                  :rounded="5"
                  @click="changePageNum(1)"
                >
                  <v-icon> mdi-magnify</v-icon>
                </v-btn>
              </div>
            </div>
          </v-card>

          <v-sheet
            class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
          >
            <v-sheet class="d-flex flex-wrap me-auto bg-shades-transparent">
              <v-sheet
                class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
              >
                <v-chip color="primary"
                  >총 {{ data.totalDataLength.toLocaleString() }}개
                </v-chip>
              </v-sheet>
              <v-sheet class="bg-shades-transparent">
                <v-responsive max-width="140" min-width="140" class="mb-2">
                  <v-select
                    v-model="data.params.pageSize"
                    density="compact"
                    :items="pageSizeOptions"
                    item-title="text"
                    item-value="value"
                    variant="outlined"
                    color="primary"
                    hide-details
                    @update:model-value="changePageNum(1)"
                  ></v-select>
                </v-responsive>
              </v-sheet>
            </v-sheet>
            <v-sheet class="justify-end mb-2 mr-3" @click="handleTerminate">
              <v-btn color="primary">Terminate </v-btn>
            </v-sheet>
            <v-sheet class="justify-end mb-2 mr-3" @click="handleRetry">
              <v-btn color="primary">Retry </v-btn>
            </v-sheet>
            <v-sheet class="justify-end mb-2 mr-3" @click="handleClone">
              <v-btn color="primary">Clone </v-btn>
            </v-sheet>
            <v-sheet class="justify-end mb-2 mr-3" @click="openComparePage">
              <v-btn color="primary">Compare </v-btn>
            </v-sheet>
            <v-sheet class="justify-end mb-2" @click="openCreateExecution">
              <v-btn color="primary">Execution </v-btn>
            </v-sheet>
          </v-sheet>

          <v-card class="rounded-lg pa-8">
            <v-col cols="12">
              <v-sheet>
                <v-table
                  density="comfortable"
                  fixed-header
                  height="625"
                  col-md-12
                  col-12
                  overflow-x-auto
                >
                  <colgroup>
                    <col style="width: 5%" />
                    <col
                      v-for="(item, i) in tableHeader"
                      :key="i"
                      :style="`width:${item.width}`"
                    />
                  </colgroup>
                  <thead>
                    <tr>
                      <th>
                        <v-checkbox
                          v-model="data.allSelected"
                          style="min-width: 36px"
                          :indeterminate="data.allSelected === true"
                          hide-details
                          @change="getSelectedAllData"
                        ></v-checkbox>
                      </th>
                      <th
                        v-for="(item, i) in tableHeader"
                        :key="i"
                        class="text-center font-weight-bold"
                        :style="`${item.style}`"
                      >
                        {{ item.label }}
                      </th>
                    </tr>
                  </thead>
                  <tbody class="text-body-2">
                    <tr
                      v-for="item in data.results"
                      :key="item.no"
                      class="text-center"
                    >
                      <td>
                        <v-checkbox
                          v-model="data.selected"
                          :value="{ deviceKey: item.deviceKey }"
                          hide-details
                          style="min-width: 36px"
                        />
                      </td>
                      <td>{{ item.no }}</td>
                      <td>{{ item.name }}</td>
                      <td>
                        <v-icon v-if="item.status === 'Succeeded'" color="green"
                          >mdi-check-circle</v-icon
                        >
                        <v-icon v-else-if="item.status === 'Failed'" color="red"
                          >mdi-close-circle</v-icon
                        >
                        <v-icon v-else color="grey">mdi-loading</v-icon>
                      </td>
                      <td>{{ item.duration }}</td>
                      <td>{{ item.experiment }}</td>
                      <td>{{ item.workflow }}</td>
                      <td>{{ item.startTime }}</td>
                      <td>{{ item.registryStatus }}</td>
                      <td style="white-space: nowrap">
                        <IconInfoBtn @on-click="openInfoModal(item)" />
                        <IconModifyBtn @on-click="openModifyModal(item)" />
                        <IconDownloadBtn @on-click="openDownloadModal(item)" />
                      </td>
                    </tr>
                  </tbody>
                </v-table>
              </v-sheet>
              <v-card-actions class="text-center mt-8 justify-center">
                <v-pagination
                  v-model="data.params.pageNum"
                  :length="data.pageLength"
                  :total-visible="10"
                  color="primary"
                  rounded="circle"
                  @update:model-value="getData"
                ></v-pagination>
              </v-card-actions>
            </v-col>
          </v-card>
        </v-card>
      </v-card>
      <v-dialog v-model="execDialogOpen" max-width="800" persistent>
        <ExecutionBaseDialog
          :model-value="execDialogOpen"
          :mode="execMode"
          :selectedData="execSelected"
          :workflowList="workflowList"
          :executionTypes="executionTypes"
          @update:modelValue="execDialogOpen = $event"
        />
      </v-dialog>
    </v-container>
  </div>
  <div class="w-100" v-else-if="openCompare">
    <CompareComponent @close="closeCompare" />
  </div>

  <div class="w-100" v-else-if="openView">
    <ViewComponent @close="closeView" />
  </div>
</template>

<style scoped></style>
