<template>
  <div>
    <div class="field" style="min-width: 360px">
      <label class="label is-flex is-align-items-center fsb-18 mb-2" for="name">
        Tên mẫu <span class="has-text-danger ml-1">*</span>
      </label>
      <div class="control">
        <input
          ref="input"
          v-model="templateName"
          id="name"
          name="name"
          class="input"
          placeholder="e.g. Thông báo quá hạn"
          :disabled="isSaving.create || isSaving.update"
        />
      </div>
    </div>
    <div class="is-flex is-justify-content-flex-end pt-2">
      <div class="buttons">
        <button
          v-if="editMode"
          class="button is-primary"
          @click="save('update')"
          :disabled="isSaving.update || templateName !== data.name || !templateName.trim()"
        >
          <span class="icon">
            <SvgIcon 
              :name="isSaving.update ? 'loading.svg' : 'save.svg'"
              type="white"
              size="16" 
            />
          </span>
          <span>Cập nhật</span>
        </button>
        <button
          class="button is-primary"
          @click="save('create')"
          :disabled="isSaving.create || templateName === data.name || !templateName.trim()"
        >
          <span class="icon">
            <SvgIcon
              :name="isSaving.create ? 'loading.svg' : 'add5.svg'"
              type="white"
              size="16" 
            />
          </span>
          <span>Tạo mới</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useNuxtApp } from "nuxt/app";

const props = defineProps({
  data: Object,
  editMode: Boolean,
  onSuccess: Function,
  onClose: Function
})

const emit = defineEmits(['close', 'success']);
const { $snackbar, $insertapi, $patchapi } = useNuxtApp();
const input = useTemplateRef('input')
const templateName = ref(props.data.name || "");
const isSaving = ref({
  create: false,
  update: false,
});

onMounted(() => {
  input.value.focus();
})

watch(() => props.data.name, (newName) => {
  templateName.value = newName || "";
});

async function save(mode) {
  if (mode === undefined) {
    $snackbar("Must specify mode: 'create' | 'update'");
    return;
  }

  if (!templateName.value.trim()) {
    $snackbar("Validation Error: Please enter a template name");
    return;
  }

  try {
    isSaving.value[mode] = true;
    const payload = { ...props.data, name: templateName.value };

    const response = mode === 'create'
      ? await $insertapi("Email_Template", payload)
      : await $patchapi("Email_Template", payload);

    if (response && response !== "error") {
      $snackbar(`Template ${mode}d successfully.`);
      if (props.onClose) props.onClose();
      if (props.onSuccess) props.onSuccess();
      emit("close");
      emit("success");
    } else {
      throw new Error("Failed to save template");
    }
  } catch (error) {
    console.error("Error saving template:", error);
    $snackbar(error.message || "Failed to save template.");
  } finally {
    isSaving.value[mode] = false;
  }
}
</script>
