<script setup lang="ts">
import IconArrowDown from "@/components/atoms/button/IconArrowDown.vue";
import IconArrowUp from "@/components/atoms/button/IconArrowUp.vue";
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import { computed, onBeforeUnmount, onMounted, watch, ref } from "vue";
import { DataGroupService } from "@/components/service/management/DataGroupService";
import { storage } from "@/utils/storage";
import { storeToRefs } from "pinia";
import { useAutoflowStore } from "@/stores/autoflowStore";

const { projectId } = storeToRefs(useAutoflowStore());

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

const isEdit = computed(() => props.mode === "edit");

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

const form = ref({ name: "", description: "" });

// 편집 데이터 → 폼
function hydrateFormFromEdit(data: any) {
  if (!data) return;
  form.value.name = data.workflowName ?? data.dsNm ?? data.name ?? "";
  form.value.description =
    data.workflowDescription ?? data.dsDesc ?? data.description ?? "";
}
onMounted(() => {
  if (isEdit.value) hydrateFormFromEdit(props.editData);
});
watch(
  () => props.editData,
  (v) => {
    if (isEdit.value) hydrateFormFromEdit(v);
  },
);

// 유저/프로젝트
function getAuthUser() {
  const authObj =
    (typeof storage?.getAuth === "function" ? storage.getAuth() : null) ??
    JSON.parse(localStorage.getItem("autoflow-auth") || "{}");
  const ui = authObj?.userInfo ?? authObj?.userinfo ?? authObj ?? {};
  return { id: Number(ui.id), username: String(ui.username ?? "").trim() };
}

function cleanUndefined<T extends Record<string, any>>(obj: T): T {
  return Object.fromEntries(
    Object.entries(obj).filter(([, v]) => v !== undefined),
  ) as T;
}

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

  const name = (form.value.name ?? "").trim(); // ← 제한 없음(한글/특수문자 OK)
  if (!name) {
    errorMsg.value = "이름을 입력하세요.";
    return;
  }

  const { id: userId, username } = getAuthUser();
  if (!userId || !username) {
    errorMsg.value = "로그인 사용자 정보를 찾을 수 없습니다.";
    return;
  }
  if (!projectId.value) {
    errorMsg.value = "프로젝트가 선택되지 않았습니다.";
    return;
  }

  try {
    saving.value = true;

    if (isEdit.value) {
      const rawId = props.editData?.id ?? props.editData?.deviceKey;
      const id = Number(rawId);
      if (!id) {
        errorMsg.value = "수정할 ID가 없습니다.";
        return;
      }

      const viewRes = await DataGroupService.view(id);
      const current = (viewRes?.data ?? viewRes) || {};

      const updatePayload = {
        id,
        dsNm: name,
        dsDesc: form.value.description ?? "",
        projectId: current.projectId,
        regUserId: current.regUserId,
        regUserNm: current.regUserNm,
        modUserId: userId,
        modUserNm: username,
      };

      const { data } = await DataGroupService.update(id, updatePayload);

      emit("saved", data);
      emit("close-modal");
    } else {
      const createPayload = {
        dsNm: name,
        dsDesc: form.value.description ?? "",
        regUserId: userId,
        regUserNm: username,
        projectId: projectId.value!,
        refType: "TRAINING_SCRIPT",
      };

      const { data } = await DataGroupService.add(createPayload);
      emit("saved", data);
      emit("close-modal");
    }
  } catch (e: any) {
    console.error("데이터그룹 저장 실패:", e);
    const status = e?.response?.status;
    const raw =
      (typeof e?.response?.data === "string"
        ? e?.response?.data
        : e?.response?.data?.message || e?.response?.data?.error) ||
      e?.message ||
      "";
    if (status === 409)
      errorMsg.value = "같은 이름의 데이터그룹이 이미 존재합니다.";
    else if (status === 400) errorMsg.value = "요청 형식이 올바르지 않습니다.";
    else if (status === 401 || status === 403)
      errorMsg.value = "권한이 없거나 로그인 정보가 만료되었습니다.";
    else errorMsg.value = raw || `요청 실패 (HTTP ${status ?? "Error"})`;
  } 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 TrainingGroup" : "Create TrainingGroup" }}
    </v-card-title>

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

      <v-form @submit.prevent="submit">
        <!-- Name: 제한 없음 -->
        <div class="mb-5">
          <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
            >TrainingGroup Name</label
          >
          <v-text-field
            v-model="form.name"
            variant="outlined"
            :disabled="saving"
            dense
            hide-details="auto"
            required
          />
        </div>

        <!-- Description: 제한 없음 -->
        <div class="mb-5">
          <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
            >Description</label
          >
          <v-textarea
            v-model="form.description"
            variant="outlined"
            :disabled="saving"
            rows="3"
            dense
            hide-details="auto"
          />
        </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>
