<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from "vue";

// 부모에서 전달받을 Props 정의
const props = defineProps<{
  modelValue: boolean;
  selectedData: { workflow: string; stepName: string } | null;
  workflowList: string[];
}>();

// v-model 및 save 이벤트를 위한 Emit 정의
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "save", payload: { workflow: string; stepName: string }): void;
}>();

// 다이얼로그 내부에서 사용할 로컬 상태
const internalWorkflow = ref(props.selectedData?.workflow || "");
const internalStepName = ref(props.selectedData?.stepName || "");

// 다이얼로그가 열릴 때 외부 데이터를 내부로 복사
watch(
  () => props.modelValue,
  (open) => {
    if (open && props.selectedData) {
      internalWorkflow.value = props.selectedData.workflow;
      internalStepName.value = props.selectedData.stepName;
    }
  },
);

// Save 버튼 클릭
const onSave = () => {
  emit("save", {
    workflow: internalWorkflow.value,
    stepName: internalStepName.value,
  });
  emit("update:modelValue", false);
};

// Close 버튼 클릭
const onClose = () => {
  emit("update:modelValue", false);
};

function onEsc(e: KeyboardEvent) {
  if (e.key === "Escape") {
    emit("update:modelValue");
  }
}

onMounted(() => window.addEventListener("keydown", onEsc));
onBeforeUnmount(() => window.removeEventListener("keydown", onEsc));
</script>

<template>
  <v-card flat>
    <!-- 타이틀 바 -->
    <v-toolbar flat color="primary" dark>
      <v-toolbar-title>Edit Workflow</v-toolbar-title>
      <v-spacer />
      <v-btn icon @click="onClose">
        <v-icon>mdi-close</v-icon>
      </v-btn>
    </v-toolbar>

    <!-- 본문 -->
    <v-card-text class="pt-6 px-6 pb-4">
      <!-- Select Workflow -->
      <v-row class="mb-6" dense>
        <v-col cols="12" sm="4">
          <div class="font-weight-medium white--text">Select Workflow</div>
        </v-col>
        <v-col cols="12">
          <v-select
            v-model="internalWorkflow"
            :items="workflowList"
            dense
            hide-details
            placeholder="Select Workflow"
            style="background: #1e1e1e; color: #fff"
          />
        </v-col>
      </v-row>

      <!-- Workflow Step Name -->
      <v-row class="mb-6" dense>
        <v-col cols="12">
          <div class="font-weight-medium white--text mb-2">
            Workflow Step Name
          </div>
          <v-text-field
            v-model="internalStepName"
            dense
            hide-details
            placeholder="Enter Workflow Step"
            style="background: #1e1e1e; color: #fff"
          />
        </v-col>
      </v-row>
    </v-card-text>

    <!-- 액션 버튼 -->
    <v-card-actions class="justify-end" style="padding: 16px 24px">
      <v-btn color="success" @click="onSave">Save</v-btn>
      <v-btn text class="white--text" @click="onClose">Close</v-btn>
    </v-card-actions>
  </v-card>
</template>
