<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import IconSettingBtn from "@/components/atoms/button/IconSettingBtn.vue";
import { onMounted, ref, nextTick } from "vue";
import ViewComponent from "@/components/templates/deployment/ViewComponent.vue";
import DeploymentDialog from "@/components/atoms/organisms/DeploymentDialog.vue";
import { ExternalAuthControllerService } from "@/components/service/management/ExternalAuthControllerService";

const openView = ref(false);
const isEditVisible = ref(false);
const loginDialog = ref(false);
const loginLoading = ref(false);
const loginForm = ref({ id: "", password: "" });
const loginError = ref("");
const isAuthenticated = ref(false);

type ExternalAuth = { id: string; name: string; token: string };
const AUTH_KEY = "external-auth";
const externalAuth = ref<ExternalAuth | null>(null);

type PackageOption = { label: string; value: string; raw: any };
const packageOptions = ref<PackageOption[]>([]);
const packagesLoading = ref(false);
const packagesError = ref("");

const tableHeader = [
  { label: "No", width: "5%", style: "word-break: keep-all;" },
  { label: "Model Name", width: "20%", style: "word-break: keep-all;" },
  { label: "Version", width: "10%", style: "word-break: keep-all;" },
  { label: "Duration", width: "10%", style: "word-break: keep-all;" },
  { label: "Deploy Status", width: "10%", style: "word-break: keep-all;" },
  { label: "Download Status", width: "10%", style: "word-break: keep-all;" },
  { label: "Deployed At", width: "15%", style: "word-break: keep-all;" },
  { label: "Action", width: "10%", style: "word-break: keep-all;" },
];

const searchOptions = [
  { searchType: "전체", searchText: "" },
  { searchType: "디바이스 별칭", searchText: "deviceAlias" },
  { searchType: "디바이스 키", searchText: "deviceKey" },
  { searchType: "사용자", searchText: "userId" },
  { searchType: "디바이스 이름", searchText: "deviceName" },
  { searchType: "디바이스 모델", searchText: "deviceModel" },
  { searchType: "디바이스 OS", searchText: "deviceOs" },
];

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

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

const handleLogin = async () => {
  try {
    loginLoading.value = true;
    loginError.value = "";

    const { id, password } = loginForm.value;
    if (!id || !password) {
      loginError.value = "ID와 비밀번호를 입력하세요.";
      return;
    }

    const res = await ExternalAuthControllerService.signIn(id, password);
    const raw = res?.data ?? res;
    if (raw == null) {
      loginError.value = "로그인에 실패했습니다. (서버 응답이 비어있습니다)";
      return;
    }
    const payload = Object.prototype.hasOwnProperty.call(raw, "data")
      ? raw.data
      : raw;
    if (!payload?.token) {
      loginError.value = "로그인에 실패했습니다. 아이디/비밀번호를 확인하세요.";
      return;
    }

    const toSave: ExternalAuth = {
      id: payload.id ?? id,
      name: payload.name ?? id,
      token: payload.token,
    };
    localStorage.setItem(AUTH_KEY, JSON.stringify(toSave));
    externalAuth.value = toSave;
    isAuthenticated.value = true;

    loginDialog.value = false;
    loginForm.value = { id: "", password: "" };

    await nextTick();
    openDeploymentModal(); // ✅ 로그인 직후 자동 오픈
  } catch (e: any) {
    loginError.value =
      e?.response?.data?.message || e?.message || "로그인에 실패했습니다.";
  } finally {
    loginLoading.value = false;
  }
};

const handleLogout = () => {
  localStorage.removeItem(AUTH_KEY);
  isAuthenticated.value = false;
  externalAuth.value = null;
  packageOptions.value = [];
};

onMounted(() => {
  const raw = localStorage.getItem(AUTH_KEY);
  if (raw) {
    try {
      const parsed = JSON.parse(raw) as ExternalAuth;
      if (parsed?.token) {
        isAuthenticated.value = true;
        externalAuth.value = parsed;
      }
    } catch {}
  }
  getData();
  getCodeList();
});

const openDeploymentModal = async () => {
  if (!isAuthenticated.value) {
    loginDialog.value = true;
    return;
  }

  data.value.selectedData = null;
  data.value.modalMode = "create";
  isEditVisible.value = true;

  packagesError.value = "";
  packageOptions.value = [];

  const auth =
    externalAuth.value ||
    (() => {
      try {
        const raw = localStorage.getItem(AUTH_KEY);
        return raw ? (JSON.parse(raw) as ExternalAuth) : null;
      } catch {
        return null;
      }
    })();

  if (!auth?.id || !auth?.token) {
    packagesError.value = "로그인 정보가 없습니다.";
    return;
  }

  try {
    packagesLoading.value = true;
    const res = await ExternalAuthControllerService.search(auth.id, auth.token);
    const body = res?.data ?? res;
    const list = body?.data?.data ?? body?.data ?? body?.result ?? body ?? [];
    const arr = Array.isArray(list) ? list : [];
    packageOptions.value = arr.map((it: any) => ({
      label: it?.package_name || it?.package_id || "Unknown",
      value: it?.package_id,
      raw: it,
    }));
  } catch (e: any) {
    packagesError.value =
      e?.response?.data?.message || e?.message || "패키지 조회 실패";
  } finally {
    packagesLoading.value = false;
  }
};

const getCodeList = () => {};
const getData = () => {
  data.value.results = [
    {
      no: 23,
      modelName: "ImageClassifier",
      version: 2,
      duration: "-",
      deployStatus: "failure",
      downloadStatus: "failure",
      deployedAt: "2025-04-28",
      key: 23,
    },
    {
      no: 22,
      modelName: "ImageClassifier",
      version: 1,
      duration: "21s",
      deployStatus: "failure",
      downloadStatus: "failure",
      deployedAt: "2025-03-21",
      key: 22,
    },
    {
      no: 21,
      modelName: "LaneDetection",
      version: 1,
      duration: "12s",
      deployStatus: "success",
      downloadStatus: "failure",
      deployedAt: "2025-03-19",
      key: 21,
    },
    {
      no: 20,
      modelName: "CustomerChurn",
      version: 1,
      duration: "-",
      deployStatus: "in_progress",
      downloadStatus: "-",
      deployedAt: "2025-02-08",
      key: 20,
    },
    {
      no: 19,
      modelName: "AnomalyDetection",
      version: 1,
      duration: "20s",
      deployStatus: "success",
      downloadStatus: "success",
      deployedAt: "2025-02-06",
      key: 19,
    },
    {
      no: 18,
      modelName: "TimeSeriesForecast",
      version: 2,
      duration: "19s",
      deployStatus: "success",
      downloadStatus: "success",
      deployedAt: "2025-01-28",
      key: 18,
    },
    {
      no: 17,
      modelName: "TextSentiment",
      version: 2,
      duration: "20s",
      deployStatus: "success",
      downloadStatus: "success",
      deployedAt: "2025-01-28",
      key: 17,
    },
  ];
  data.value.totalDataLength = data.value.results.length;
  const total = data.value.totalDataLength;
  const size = data.value.params.pageSize;
  data.value.pageLength =
    total % size === 0 ? total / size : Math.ceil(total / size);
};

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 = (_: any) => {};
const removeData = (_: any) => {};
const handleRemoveData = () => {};
const handleRefresh = () => alert("Refresh 작업 진행중...");
const openInfoModal = () => {
  data.value.modalMode = "info";
  openView.value = true;
};
const closeDetail = () => {
  openView.value = false;
};
const changePageNum = (page: number) => {
  data.value.params.pageNum = page;
  getData();
};
const openSettingModal = (selectedItem: any) => {
  data.value.selectedData = selectedItem;
  data.value.modalMode = "setting";
  openView.value = true;
};
const openModifyModal = (selectedItem: any) => {
  data.value.selectedData = selectedItem;
  data.value.modalMode = "modify";
  data.value.isModalVisible = true;
};
const closeModal = () => {
  data.value.isModalVisible = false;
  data.value.selectedData = null;
};
const closeCreateModal = () => {
  data.value.isModalVisible = false;
  isEditVisible.value = false;
};
const getSelectedAllData = () => {
  data.value.selected = data.value.allSelected
    ? data.value.results.map((item: any) => ({ deviceKey: item.deviceKey }))
    : [];
};
</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>Deployment</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-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-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-responsive>
              </v-sheet>
            </v-sheet>

            <v-sheet class="justify-end mb-2">
              <v-btn
                class="mr-4"
                color="primary"
                :rounded="5"
                @click="isAuthenticated ? handleLogout() : (loginDialog = true)"
              >
                <v-icon start>{{
                  isAuthenticated ? "mdi-logout" : "mdi-login"
                }}</v-icon>
                {{ isAuthenticated ? "Logout" : "Login" }}
              </v-btn>
              <v-btn color="info" class="mr-4" @click="handleRefresh"
                >Refresh</v-btn
              >
              <v-btn color="info" @click="openDeploymentModal"
                >Deployment</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"
                        />
                      </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 class="text-start">{{ item.modelName }}</td>
                      <td>{{ item.version }}</td>
                      <td>{{ item.duration }}</td>
                      <td>
                        <v-icon
                          v-if="item.deployStatus === 'success'"
                          color="success"
                          >mdi-checkbox-marked-circle</v-icon
                        >
                        <v-icon
                          v-else-if="item.deployStatus === 'in_progress'"
                          spin
                          >mdi-loading</v-icon
                        >
                        <v-icon v-else color="error">mdi-close-circle</v-icon>
                      </td>
                      <td>
                        <v-icon
                          v-if="item.downloadStatus === 'success'"
                          color="success"
                          >mdi-checkbox-marked-circle</v-icon
                        >
                        <v-icon
                          v-else-if="item.downloadStatus === 'in_progress'"
                          spin
                          >mdi-loading</v-icon
                        >
                        <v-icon
                          v-else-if="item.downloadStatus === 'failure'"
                          color="error"
                          >mdi-close-circle</v-icon
                        >
                        <span v-else>-</span>
                      </td>
                      <td>{{ item.deployedAt }}</td>
                      <td style="white-space: nowrap">
                        <IconInfoBtn @on-click="openInfoModal(item)" />
                        <IconDeployment @click="redeploy(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-card-actions>
            </v-col>
          </v-card>
        </v-card>
      </v-card>

      <v-dialog v-model="isEditVisible" max-width="800" persistent>
        <DeploymentDialog
          :edit-data="data.selectedData"
          :mode="data.modalMode"
          :packages="packageOptions"
          :packages-loading="packagesLoading"
          :packages-error="packagesError"
          @close-modal="closeCreateModal"
          @handle-data="saveData"
          :user-option="data.userOption"
        />
      </v-dialog>

      <v-dialog v-model="loginDialog" max-width="450" persistent>
        <v-card>
          <v-card-title
            class="text-white font-weight-bold text-h6"
            style="background-color: #1976d2"
            >외부 로그인</v-card-title
          >
          <v-card-text class="pa-6">
            <v-form @submit.prevent="handleLogin">
              <div class="mb-5">
                <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
                  >ID</label
                >
                <v-text-field
                  v-model="loginForm.id"
                  variant="outlined"
                  :disabled="loginLoading"
                  dense
                  hide-details="auto"
                  autocomplete="username"
                  required
                  @keyup.enter.prevent="handleLogin"
                />
              </div>
              <div class="mb-5">
                <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
                  >Password</label
                >
                <v-text-field
                  v-model="loginForm.password"
                  variant="outlined"
                  :disabled="loginLoading"
                  dense
                  hide-details="auto"
                  type="password"
                  autocomplete="current-password"
                  required
                  @keyup.enter.prevent="handleLogin"
                />
              </div>
              <div v-if="loginError" class="mt-3 text-error">
                {{ loginError }}
              </div>
            </v-form>
          </v-card-text>
          <v-card-actions class="justify-end" style="padding: 16px 24px">
            <v-btn color="success" :loading="loginLoading" @click="handleLogin"
              >Login</v-btn
            >
            <v-btn
              text
              class="white--text"
              :disabled="loginLoading"
              @click="loginDialog = false"
              >Close</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </div>

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

<style scoped></style>
