<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 600px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader
          :title="replyItem ? 'Editar Comentário' : 'Responder Suporte'"
          @close="onDialogCancel"
        />

        <DefaultForm ref="formRef" @submit="onOKClick">
          <q-card-section class="q-pt-sm">
            <DefaultInput
              v-model="replyText"
              label="Descreva a resposta"
              type="textarea"
              class="col-12"
            />
          </q-card-section>

          <q-card-actions align="right" class="q-px-md q-pb-md">
            <q-btn
              outline
              color="primary"
              label="Cancelar"
              @click="onDialogCancel"
            />
            <q-btn
              color="primary"
              :label="replyItem ? 'Salvar' : 'Responder'"
              type="submit"
              :loading="loading"
            />
          </q-card-actions>
        </DefaultForm>
      </q-card>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { useDialogPluginComponent } from "quasar";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import { createSupportReply, updateSupportReply } from "src/api/support_reply";

defineEmits([...useDialogPluginComponent.emits]);

const { ticketId, replyItem } = defineProps({
  ticketId: {
    type: Number,
    required: true,
  },
  replyItem: {
    type: Object,
    default: null,
  },
});

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
  useDialogPluginComponent();

const loading = ref(false);
const replyText = ref(replyItem?.reply ?? null);

const onOKClick = async () => {
  loading.value = true;
  try {
    if (replyItem) {
      await updateSupportReply(ticketId, replyItem.id, { reply: replyText.value });
    } else {
      await createSupportReply(ticketId, { reply: replyText.value });
    }
    onDialogOK(true);
  } finally {
    loading.value = false;
  }
};
</script>
