<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import { onMounted, ref } from "vue";
import { storage } from "@/utils/storage";
import ViewComponent from "@/components/templates/run/experiment/ViewComponent.vue";
import ExperimentCreateDialog from "@/components/atoms/organisms/ExperimentCreateDialog.vue";
import { ExperimentService } from "@/components/service/management/ExperimentService";
import { commonStore } from "@/stores/commonStore";

const store = commonStore();
const execSelected = ref<any>(null);
const openView = ref(false);
const username = ref<string>("");
const selectedExperiment = ref<{
  name: string;
  description: string;
  createdDate: string;
  createdID: string;
  deviceKey: number;
} | null>(null);

// ===== 헤더 =====
const tableHeader = [
  { label: "Experiment Name", width: "20%", style: "word-break: keep-all;" },
  { label: "Description", width: "20%", style: "word-break: keep-all;" },
  { label: "Created Date", width: "20%", style: "word-break: keep-all;" },
  { label: "Created ID", width: "20%", style: "word-break: keep-all;" },
  { label: "Action", width: "20%", style: "word-break: keep-all;" },
];

// ===== 검색/페이지네이션 (데이터셋/워크플로우와 '동일') =====
type SearchType = "전체" | "제목" | "작성자";

const searchOptions = [
  { label: "전체", value: "전체" as SearchType },
  { label: "제목", value: "제목" as SearchType },
  { label: "작성자", value: "작성자" as SearchType },
];

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

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

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

// ===== 유틸 =====
function readUsernameFromStorage(): string {
  try {
    const raw =
      storage?.get?.("autoflow-auth") ??
      storage?.getAuth?.() ??
      localStorage.getItem("autoflow-auth") ??
      null;
    const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
    const u1 = auth?.userInfo?.username;
    const u2 = auth?.username;
    const u3 = auth?.userInfo?.userName;
    const u4 = auth?.userInfo?.email?.split?.("@")?.[0];
    return (u1 || u2 || u3 || u4 || "").toString();
  } catch {
    return "";
  }
}
const getProjectId = (): number => {
  const v = Number(localStorage.getItem("projectId"));
  return Number.isFinite(v) ? v : 0;
};
const fmtDate = (v?: string) =>
  v ? String(v).replace("T", " ").slice(0, 19) : "";

// 서버 → 테이블 Row
const toRow = (e: any) => ({
  name: e.displayName,
  description: e.description,
  createdDate: fmtDate(e.lastUpdateTime),
  deviceKey: e.id,
  createdID: e.regUserId,
  mlFlowId: e.mlFlowId ?? e.mlFlowExperimentId ?? "",
});

// ===== 목록 조회 (데이터셋 화면과 같은 흐름) =====
const fetchList = async () => {
  const projectId = getProjectId();
  if (!projectId) {
    console.warn("[Experiments] projectId 없음 — 프로젝트 먼저 선택");
    data.value.results = [];
    data.value.totalElements = 0;
    data.value.pageLength = 0;
    return;
  }

  const { pageNum, pageSize, searchType, searchText } = 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,
  };

  try {
    const res = await ExperimentService.search(payload as any);
    const result = res?.data ?? res;
    let list = result?.content ?? [];

    if (needLocalFilter) {
      const kw = keyword.toLowerCase();
      if (mapped === "TITLE") {
        list = list.filter((x: any) =>
          String(x?.name ?? x?.displayName ?? "")
            .toLowerCase()
            .includes(kw),
        );
      } else if (mapped === "AUTHOR") {
        list = list.filter((x: any) =>
          String(x?.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);

      data.value.results = pageSlice.map(toRow);
      data.value.totalElements = totalElements;
      data.value.pageLength = totalPages;
      return;
    }

    data.value.results = (list as any[]).map(toRow);
    data.value.totalElements = result?.totalElements ?? list.length;
    data.value.pageLength = result?.totalPages ?? 1;
  } catch (err) {
    console.error("[Experiments] 조회 에러:", err);
    data.value.results = [];
    data.value.totalElements = 0;
    data.value.pageLength = 1;
  }
};

// ===== 검색/페이지 조작 =====
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 removeOne = (id: number) =>
    ExperimentService.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;
  };

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

// ===== 상세 & 생성 모달  =====
const closeView = () => {
  openView.value = false;
};

const openInfoModal = (item: any) => {
  execSelected.value = item;
  openView.value = true;
};
const openCreateModal = () => {
  data.value.modalMode = "create";
  data.value.selectedData = {
    username: username.value,
    projectId: getProjectId(),
  };
  data.value.isCreateVisible = true;
};
const closeModal = () => {
  data.value.isCreateVisible = false;
  data.value.selectedData = null;
};

onMounted(() => {
  username.value = readUsernameFromStorage();
  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>Experiment</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
                />
              </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-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-responsive>
              </v-sheet>
            </v-sheet>

            <v-sheet class="justify-end mb-2">
              <v-btn color="primary" @click="openCreateModal"
                >Create Experiment</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"
                  overflow-x-auto
                >
                  <colgroup>
                    <col
                      v-for="(item, i) in tableHeader"
                      :key="i"
                      :style="`width:${item.width}`"
                    />
                  </colgroup>
                  <thead>
                    <tr>
                      <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 clickable-row"
                      role="button"
                      tabindex="0"
                      @click="openInfoModal(item)"
                      @keydown.enter.prevent="openInfoModal(item)"
                      @keydown.space.prevent="openInfoModal(item)"
                    >
                      <td>{{ item.name }}</td>
                      <td>{{ item.description }}</td>
                      <td>{{ item.createdDate }}</td>
                      <td>{{ item.createdID }}</td>
                      <td style="white-space: nowrap">
                        <span @click.stop @keydown.stop>
                          <IconInfoBtn @on-click="openInfoModal(item)" />
                        </span>
                        <span @click.stop @keydown.stop>
                          <IconDeleteBtn
                            @on-click="
                              removeData([{ deviceKey: item.deviceKey }])
                            "
                          />
                        </span>
                      </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-card-actions>
            </v-col>
          </v-card>
        </v-card>
      </v-card>
    </v-container>

    <!-- 생성 다이얼로그 -->
    <v-dialog v-model="data.isCreateVisible" max-width="600" persistent>
      <ExperimentCreateDialog
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeModal"
        @saved="fetchList"
        @handle-data="() => {}"
      />
    </v-dialog>
  </div>

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

<style scoped>
.clickable-row {
  cursor: pointer;
}
.clickable-row:hover {
  background: rgba(255, 255, 255, 0.06);
}
.clickable-row:focus {
  outline: 2px solid #3b82f6;
  outline-offset: -2px;
}
</style>
