<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { storage } from "@/utils/storage";
import { storeToRefs } from "pinia";
import { useAutoflowStore } from "@/stores/autoflowStore";
import type { AxiosError } from "axios";
import { WorkflowStepService } from "@/components/service/management/WorkflowStepService";
import { WorkflowService } from "@/components/service/management/WorkflowService"; // ⬅️ 추가

const props = defineProps<{ editData: any; mode: "create" | "edit" }>();
const emit = defineEmits<{
  (e: "close-modal"): void;
  (e: "saved", value: any): void;
}>();

const isEdit = computed(() => props.mode === "edit");
const { projectId } = storeToRefs(useAutoflowStore());

const saving = ref(false);
const errorMsg = ref("");

// ===== 워크플로우 드롭다운 상태 =====
const workflowsLoading = ref(false);
const workflowOptions = ref<Array<{ title: string; value: number }>>([]);
const selectedWorkflowId = ref<number | null>(null);

async function fetchWorkflows() {
  try {
    workflowsLoading.value = true;
    // 1) /api/workflows (배열) or 2) search 결과(content) 모두 대응
    const res =
      (await (WorkflowService as any).list?.()) ??
      (await (WorkflowService as any).search?.({ page: 0, size: 1000 }));
    const raw = res?.data ?? res;
    const list = Array.isArray(raw?.content)
      ? raw.content
      : Array.isArray(raw)
        ? raw
        : [];

    const filtered = projectId.value
      ? list.filter((w: any) => Number(w.projectId) === Number(projectId.value))
      : list;

    workflowOptions.value = filtered.map((w: any) => ({
      title:
        (w.workflowName || w.name || `Workflow #${w.id}`) +
        (w.version ? ` (v${w.version})` : ""),
      value: Number(w.id),
    }));

    // 수정 모드에서 값 복원
    if (isEdit.value && selectedWorkflowId.value == null) {
      const wid =
        props.editData?.workflowStepId ??
        props.editData?.workflowId ??
        props.editData?.workflow?.id ??
        null;
      if (wid != null) selectedWorkflowId.value = Number(wid);
    }
  } catch (e) {
    console.error("[Dialog] 워크플로우 목록 조회 실패:", e);
    workflowOptions.value = [];
  } finally {
    workflowsLoading.value = false;
  }
}

// ===== 폼 =====
type StepStatus = "Running" | "Success" | "Fail";
const form = ref({ stepName: "", status: "Running" as StepStatus });

function hydrateFormFromEdit(data: any) {
  if (!data) return;
  form.value.stepName = data?.stepName ?? data?.name ?? "";
  form.value.status = (data?.status as StepStatus) ?? "Running";

  // 드롭다운 값 복원(가능한 키 모두 시도)
  const wid =
    data?.workflowStepId ?? data?.workflowId ?? data?.workflow?.id ?? null;
  selectedWorkflowId.value = wid != null ? Number(wid) : null;
}

onMounted(() => {
  if (isEdit.value) hydrateFormFromEdit(props.editData);
  fetchWorkflows();
});
watch(
  () => props.editData,
  (v) => {
    if (isEdit.value) hydrateFormFromEdit(v);
  },
);
watch(projectId, () => fetchWorkflows());

const nowLocalIso = (): string => {
  const t = new Date(Date.now() - new Date().getTimezoneOffset() * 60000);
  return t.toISOString().slice(0, 23);
};

const regUserId = (() => {
  try {
    const authObj =
      (typeof storage?.getAuth === "function" ? storage.getAuth() : null) ??
      JSON.parse(localStorage.getItem("autoflow-auth") || "{}");
    return (
      authObj?.userInfo?.username ??
      authObj?.userinfo?.username ??
      authObj?.username ??
      authObj?.userId ??
      ""
    );
  } catch {
    return "";
  }
})();

async function submit() {
  errorMsg.value = "";

  // 검증
  const stepName = form.value.stepName.trim();
  if (!stepName) return (errorMsg.value = "Step Name은 필수입니다.");
  if (!regUserId)
    return (errorMsg.value = "로그인 사용자 정보를 찾을 수 없습니다.");
  if (!projectId.value)
    return (errorMsg.value = "프로젝트가 선택되지 않았습니다.");
  if (!selectedWorkflowId.value)
    return (errorMsg.value = "Workflow를 선택해주세요.");

  const payload: any = {
    stepName,
    status: form.value.status,
    regUserId,
    regDt: nowLocalIso(),
    version: 1,
    projectId: projectId.value,
    workflowStepId: selectedWorkflowId.value,
  };

  try {
    saving.value = true;
    if (isEdit.value) {
      const rawId = props.editData?.id ?? props.editData?.deviceKey;
      const id = Number(rawId);
      if (!id) return (errorMsg.value = "수정할 ID가 없습니다.");
      const { data } = await WorkflowStepService.update(id, payload);
      emit("saved", data);
    } else {
      const { data } = await WorkflowStepService.add(payload);
      emit("saved", data);
    }
    emit("close-modal");
  } catch (e) {
    console.error("워크플로우 스텝 저장 실패:", e as AxiosError);
    errorMsg.value = "저장에 실패했습니다. 잠시 후 다시 시도하세요.";
  } finally {
    saving.value = false;
  }
}

function onEsc(e: KeyboardEvent) {
  if (e.key === "Escape") emit("close-modal");
}
onMounted(() => window.addEventListener("keydown", onEsc));
onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
</script>

<template>
  <v-card>
    <v-card-title
      class="text-white font-weight-bold text-h6"
      style="background-color: #1976d2"
    >
      {{ isEdit ? "Edit Workflow Step" : "Create Workflow Step" }}
    </v-card-title>

    <v-card-text class="pa-6">
      <div class="text-subtitle-1 font-weight-medium mb-4">
        Workflow Step Information
      </div>

      <v-form @submit.prevent="submit">
        <!-- 워크플로우 드롭다운 -->

        <div class="mb-5">
          <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
            >Step Name</label
          >
          <v-text-field
            v-model="form.stepName"
            variant="outlined"
            :disabled="saving"
            dense
            hide-details
            required
          />
        </div>

        <div class="mb-5">
          <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
            >Workflow</label
          >
          <v-select
            v-model="selectedWorkflowId"
            :items="workflowOptions"
            item-title="title"
            item-value="value"
            variant="outlined"
            :loading="workflowsLoading"
            :disabled="saving || workflowsLoading"
            dense
            hide-details
            placeholder="워크플로우를 선택하세요"
          />
        </div>

        <div class="mb-5">
          <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
            >Status</label
          >
          <v-select
            v-model="form.status"
            :items="['Running', 'Success', 'Fail']"
            variant="outlined"
            :disabled="saving"
            dense
            hide-details
          />
        </div>

        <div v-if="errorMsg" class="mt-3 text-error">{{ errorMsg }}</div>
      </v-form>
    </v-card-text>

    <v-card-actions class="justify-end" style="padding: 16px 24px">
      <v-btn color="success" :loading="saving" @click="submit">{{
        isEdit ? "Update" : "Save"
      }}</v-btn>
      <v-btn
        text
        class="white--text"
        :disabled="saving"
        @click="$emit('close-modal')"
        >Close</v-btn
      >
    </v-card-actions>
  </v-card>
</template>
