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

import { commonStore } from "@/stores/commonStore";
import { WorkflowService } from "@/components/service/management/workflowService";

import ViewComponent from "@/components/templates/workflow/ViewComponent.vue";
import WorkflowsBaseDialog from "@/components/atoms/organisms/WorkflowsBaseDialog.vue";
import WorkflowsUploadDialog from "@/components/atoms/organisms/WorkflowsUploadDialog.vue";
import WorkflowsRunDialog from "@/components/atoms/organisms/WorkflowsRunDialog.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconRunBtn from "@/components/atoms/button/IconRunBtn.vue";
dayjs.extend(utc);
dayjs.extend(tz);
const KST = "Asia/Seoul";
const store = commonStore();
const openView = ref(false);
type SearchType = "전체" | "제목" | "작성자";

const isRunVisible = ref(false);
const selectedRun = ref<any | null>(null);

const tableHeader = [
  { label: "No", width: "5%", style: "word-break: keep-all;" },
  { label: "Workflow Name", width: "18%", style: "word-break: keep-all;" },
  { label: "Description", width: "28%", style: "word-break: keep-all;" },
  { label: "Version", width: "10%", style: "word-break: keep-all;" },
  { label: "Kubeflow Status", width: "12%", style: "word-break: keep-all;" },
  { label: "Created DateTime", width: "15%", style: "word-break: keep-all;" },
  { label: "Action", width: "12%", style: "word-break: keep-all;" },
];
const searchOptions = [
  { label: "전체", value: "전체" as SearchType },
  { label: "제목", value: "제목" as SearchType },
  { label: "사용자", value: "작성자" as SearchType },
];

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

const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
  "": "ALL",
  전체: "ALL",
  제목: "TITLE",
  작성자: "AUTHOR",
};

const data = ref({
  params: {
    pageNum: 1,
    pageSize: 10,
    searchType: "전체" as SearchType,
    searchText: "",
  },
  results: [] as any[],
  totalElements: 0,
  pageLength: 0,
  modalMode: "" as "create" | "edit" | "upload" | "",
  selectedData: null as any,
  allSelected: false,
  selected: [] as Array<{ deviceKey: number }>,
  isCreateVisible: false,
  isUploadVisible: false,
  isModalVisible: false,
  isConfirmDialogVisible: false,
  userOption: [] as any[],
});

const formatDateTime = (
  v?: string | number | Date,
  fmt = "YYYY-MM-DD HH:mm:ss",
) => (v ? dayjs(v).tz(KST).format(fmt) : "");

const toRow = (w: any, no: number) => ({
  no,
  name: w.name,
  description: w.description,
  version: w.version,
  kubeflowStatus: w.kubeflowStatus,
  registDt: w.regDt,
  deviceKey: w.id,
  pipelineId: w.pipelineId ?? w.pipeline_id ?? "",
});

const fetchList = () => {
  const projectId = Number(localStorage.getItem("projectId"));
  if (!projectId) {
    console.warn("[Workflows] projectId 없음 — 프로젝트 먼저 선택");
    data.value.results = [];
    data.value.totalElements = 0;
    data.value.pageLength = 0;
    return;
  }

  const { pageNum, searchText, searchType } = data.value.params;

  // 매핑 및 로컬 필터링 필요 여부 판단
  const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
  const keyword = (searchText || "").trim();
  const needLocalFilter = mapped !== "ALL" && keyword.length > 0;

  let reqPage = data.value.params.pageNum;
  let reqSize = data.value.params.pageSize;
  if (needLocalFilter) {
    reqPage = 0;
    reqSize = 1000;
  }
  const payload = {
    projectId,
    page: reqPage,
    size: reqSize,
    keyword,
    searchType: mapped,
  };

  WorkflowService.search(payload)
    .then((res: any) => {
      if (res.status !== 200) return;

      const result = res.data;
      let list = result?.content ?? [];

      if (needLocalFilter) {
        const kw = keyword.toLowerCase();

        if (mapped === "TITLE") {
          list = list.filter((w: any) =>
            String(w?.name ?? "")
              .toLowerCase()
              .includes(kw),
          );
        } else if (mapped === "AUTHOR") {
          list = list.filter((w: any) =>
            String(w?.regUserId ?? "")
              .toLowerCase()
              .includes(kw),
          );
        }

        const uiSize = data.value.params.pageSize;
        const totalElements = list.length;
        const totalPages = Math.max(1, Math.ceil(totalElements / uiSize));
        const safePage = Math.min(Math.max(1, pageNum), totalPages);
        const start = (safePage - 1) * uiSize;
        const pageSlice = list.slice(start, start + uiSize);

        // 이 페이지의 첫 행 번호(내림차순)
        const firstNo = totalElements - start;

        data.value.results = pageSlice.map((w: any, i: number) =>
          toRow(w, firstNo - i),
        );
        data.value.totalElements = totalElements;
        data.value.pageLength = totalPages;
        return;
      }

      const totalElements = result.totalElements;
      const totalPages = result.totalPages;
      const serverPage = result.pageable.pageNumber;
      const serverSize = result.pageable.pageSize;
      const offset =
        typeof result.pageable.offset === "number"
          ? result.pageable.offset
          : serverPage * serverSize;
      const firstNo = totalElements - offset;

      data.value.results = list.map((w: any, i: number) =>
        toRow(w, firstNo - i),
      );
      data.value.totalElements = totalElements;
      data.value.pageLength = totalPages;
    })
    .catch((err: any) => console.error("워크플로우 조회 에러:", err));
};

const doSearch = () => {
  data.value.params.pageNum = 1;
  fetchList();
};

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

const changePageSize = (size: number) => {
  data.value.params.pageSize = size;
  data.value.params.pageNum = 1;
  fetchList();
};

const removeData = (value?: Array<{ deviceKey: number }>) => {
  const removeList = value ?? data.value.selected;
  if (!removeList || removeList.length === 0) return;

  const ids = removeList.map((x) => x.deviceKey);
  const remove = (id: number) =>
    WorkflowService.delete(id).then((res) => {
      if (res.status < 200 || res.status >= 300) return Promise.reject(res);
    });

  const after = () => {
    if (
      ids.length >= data.value.results.length &&
      data.value.params.pageNum > 1
    ) {
      data.value.params.pageNum -= 1;
    }
    fetchList();
    data.value.isConfirmDialogVisible = false;
    data.value.selected = [];
    data.value.allSelected = false;
  };
  console.log(ids.length);

  if (ids.length === 1) {
    remove(ids[0])
      .then(() => {
        store.setSnackbarMsg({
          color: "success",
          text: "삭제되었습니다.",
          result: 200,
        });
        after();
      })
      .catch((err) => {
        store.setSnackbarMsg({
          color: "warning",
          text: "삭제 실패",
          result: 500,
        });
        console.error(err);
      });
  } else {
    Promise.all(ids.map(remove))
      .then(() => {
        store.setSnackbarMsg({
          color: "success",
          text: "모두 삭제되었습니다.",
          result: 200,
        });
      })
      .catch((err) => {
        store.setSnackbarMsg({
          color: "warning",
          text: "일부 삭제 실패",
          result: 500,
        });
        console.error(err);
      })
      .finally(after);
  }
};

const handleRemoveData = () => {
  if (data.value.selected.length === 0) return;
  if (data.value.allSelected || data.value.selected.length !== 1) {
    data.value.isConfirmDialogVisible = true;
    return;
  }
  removeData();
};

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

const openDetailModal = (selectedItem: any) => {
  data.value.selectedData = selectedItem;
  openView.value = true;
};

const closeDetail = () => (openView.value = false);
const closeRunModal = () => (isRunVisible.value = false);

const openRunModal = (item: any) => {
  selectedRun.value = item;
  isRunVisible.value = true;
};

const openModifyModal = (item: any) => {
  data.value.selectedData = {
    id: item.deviceKey,
    workflowName: item.name,
    workflowDescription: item.description,
  };
  data.value.modalMode = "edit";
  data.value.isCreateVisible = true;
};

const openCreateModal = () => {
  data.value.selectedData = null;
  data.value.modalMode = "create";
  data.value.isCreateVisible = true;
};

const openUploadModal = () => {
  data.value.selectedData = null;
  data.value.modalMode = "upload";
  data.value.isUploadVisible = true;
};

const closeCreateModal = () => {
  data.value.isModalVisible = false;
  data.value.isCreateVisible = false;
};

const closeUploadModal = () => {
  data.value.isModalVisible = false;
  data.value.isUploadVisible = false;
};

watch(
  () => data.value.isCreateVisible,
  (now, prev) => {
    if (prev && !now) fetchList();
  },
);

watch(
  () => data.value.isUploadVisible,
  (now, prev) => {
    if (prev && !now) fetchList();
  },
);

onMounted(() => {
  fetchList();
});
</script>

<template>
  <div class="w-100" v-if="!openView">
    <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">Workflows</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="label"
                  item-value="value"
                  hide-details
                  @update:model-value="doSearch"
                />
              </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="doSearch"
                ></v-text-field>
              </v-responsive>

              <div class="ml-3">
                <v-btn
                  size="large"
                  color="primary"
                  :rounded="5"
                  @click="doSearch"
                >
                  <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.totalElements.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="changePageSize"
                  ></v-select>
                </v-responsive>
              </v-sheet>
            </v-sheet>
            <v-sheet class="justify-end mb-2">
              <!-- <v-btn color="info" class="mr-4" @click="openUploadModal"
                >Upload Workflow
              </v-btn> -->
              <v-btn color="info" @click="openCreateModal"
                >Create Workflow
              </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, i) in data.results"
                      :key="i"
                      class="text-center"
                    >
                      <td>
                        <v-checkbox
                          v-model="data.selected"
                          hide-details
                          :value="{
                            deviceKey: item.deviceKey,
                          }"
                        ></v-checkbox>
                      </td>
                      <td>{{ item.no }}</td>
                      <td>{{ item.name }}</td>
                      <td>{{ item.description }}</td>
                      <td>{{ item.version }}</td>
                      <td>{{ item.kubeflowStatus }}</td>
                      <td>{{ formatDateTime(item.registDt) }}</td>
                      <td style="white-space: nowrap">
                        <IconRunBtn @on-click="openRunModal(item)" />
                        <IconInfoBtn @on-click="openDetailModal(item)" />
                        <!-- <IconModifyBtn @on-click="openModifyModal(item)" /> -->
                        <IconDeleteBtn
                          @on-click="
                            removeData([{ deviceKey: item.deviceKey }])
                          "
                        />
                      </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="changePageNum"
                ></v-pagination>
              </v-card-actions>
            </v-col>
          </v-card>
        </v-card>
      </v-card>
    </v-container>
    <v-dialog v-model="data.isCreateVisible" max-width="800" persistent>
      <WorkflowsBaseDialog
        :key="data.modalMode + String(data.selectedData?.deviceKey ?? '')"
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeCreateModal"
      />
    </v-dialog>
    <v-dialog v-model="data.isUploadVisible" max-width="800" persistent>
      <WorkflowsUploadDialog
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeUploadModal"
      />
    </v-dialog>
    <v-dialog v-model="isRunVisible" max-width="600" persistent>
      <WorkflowsRunDialog
        :pipeline-id="selectedRun?.pipelineId"
        :display-name="`Run of ${selectedRun?.name ?? 'Pipeline'} (${new Date().toLocaleString()})`"
        :description="selectedRun?.description || ''"
        @close-modal="closeRunModal"
      />
    </v-dialog>
  </div>

  <div class="w-100" v-else>
    <ViewComponent
      v-if="data.selectedData"
      :id="data.selectedData.deviceKey"
      @close="closeDetail"
    />
  </div>
</template>

<style scoped></style>
