<script setup lang="ts">
import { computed, ref, watch, onMounted, onBeforeUnmount } from "vue";
import { storeToRefs } from "pinia";
import { useAutoflowStore } from "@/stores/autoflowStore";
import { AttachmentsService } from "@/components/service/management/AttachmentsService";
import type { AxiosError } from "axios";

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 { projectId } = storeToRefs(useAutoflowStore());
const saving = ref(false);
const errorMsg = ref("");

const form = ref({
  name: "",
  description: "",
  file: null as any,
});

function hydrateFormFromEdit(d: any) {
  if (!d) return;
  form.value.name = (d?.name ?? d?.title ?? "") + "";
  form.value.description = (d?.description ?? "") + "";
}

const getRefId = () => String(props.editData?.refId ?? "0");
onMounted(() => {
  if (isEdit.value) hydrateFormFromEdit(props.editData);
});
watch(
  () => props.editData,
  (v) => {
    if (isEdit.value) hydrateFormFromEdit(v);
  },
);

const dialogTitle = computed(() =>
  isEdit.value ? "Edit Training Script" : "Create Training Script",
);

// 로그인 사용자
const regUserId = (() => {
  try {
    const raw = localStorage.getItem("autoflow-auth") || "{}";
    const auth = JSON.parse(raw);
    return (
      auth?.userInfo?.username ??
      auth?.userinfo?.username ??
      auth?.username ??
      auth?.userId ??
      ""
    );
  } catch {
    return "";
  }
})();

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

  const title = (form.value.name || "").trim();
  const desc = (form.value.description || "").trim();
  const fileObj = Array.isArray(form.value.file)
    ? form.value.file[0]
    : form.value.file;

  if (!title) return (errorMsg.value = "Training Script Title은 필수입니다.");
  if (!regUserId)
    return (errorMsg.value = "로그인 사용자 정보를 찾을 수 없습니다.");

  try {
    saving.value = true;

    if (isEdit.value) {
      // 수정: 스웨거 기준 file required → 새 파일 선택 필요
      if (!fileObj) return (errorMsg.value = "수정할 새 파일을 선택해주세요.");

      const fd = new FormData();
      fd.append("title", title);
      fd.append("description", desc);
      fd.append("regUserId", regUserId);
      fd.append("projectId", String(projectId.value));
      fd.append("file", fileObj);

      const id = props.editData?.id ?? props.editData?.deviceKey;
      await AttachmentsService.update(id, fd as any);
    } else {
      if (!fileObj) return (errorMsg.value = "업로드할 파일을 선택해주세요.");
      if (!projectId.value)
        return (errorMsg.value = "프로젝트가 선택되지 않았습니다.");

      const fd = new FormData();
      fd.append("refId", getRefId());
      fd.append("refType", "TRAINING_SCRIPT");
      fd.append("title", title);
      fd.append("description", desc);
      fd.append("version", "1");
      fd.append("regUserId", regUserId);
      fd.append("projectId", String(projectId.value));
      fd.append("file", fileObj);

      await AttachmentsService.upload(fd as any);
    }

    emit("saved", { ok: true });
    emit("close-modal");
  } catch (e) {
    console.error("[Training Script] 저장 실패:", 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 class="rounded-lg overflow-hidden">
    <v-card-title
      class="text-white font-weight-bold text-h6"
      style="background-color: #1976d2"
    >
      {{ dialogTitle }}
    </v-card-title>

    <v-card-text class="pa-6">
      <v-form @submit.prevent="submit">
        <div class="mb-5">
          <label class="text-subtitle-2 font-weight-medium mb-1 d-block"
            >Training Script Title</label
          >
          <v-text-field
            v-model="form.name"
            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"
            >Description</label
          >
          <v-text-field
            v-model="form.description"
            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"
            >File</label
          >
          <v-file-input
            v-model="form.file"
            label="Upload File"
            :disabled="saving"
            outlined
            dense
            hide-details
            :required="true"
          />
        </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>
