<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <div style="width: 100%; max-width: 500px">
      <q-card class="overflow-hidden" style="width: 100%">
        <DefaultDialogHeader title="Encerrar Ticket" @close="onDialogCancel" />

        <q-card-section class="q-pt-sm column q-gutter-y-md">
          <DefaultSelect
            v-model="resolved"
            label="A solicitação foi resolvida?"
            :options="resolvedOptions"
            emit-value
            map-options
          />

          <p v-if="resolved !== null" class="text-body2 q-mb-none">
            <template v-if="resolved">
              Sua solicitação foi resolvida com sucesso, hora de finalizar este suporte.
            </template>
            <template v-else>
              Sua solicitação não foi resolvida, finalize o suporte.
            </template>
          </p>
        </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
            v-if="resolved !== null && ticket.status === 'in_progress'"
            color="primary"
            label="Encerrar"
            :loading="loading"
            @click="onOKClick"
          />
        </q-card-actions>
      </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 DefaultSelect from "src/components/defaults/DefaultSelect.vue";
import { updateSupportTicket } from "src/api/support_ticket";

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

const { ticket } = defineProps({
  ticket: {
    type: Object,
    required: true,
  },
});

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

const loading = ref(false);
const resolved = ref(null);

const resolvedOptions = [
  { label: "Sim", value: true },
  { label: "Não", value: false },
];

const onOKClick = async () => {
  loading.value = true;
  try {
    const status = resolved.value ? "resolved" : "unresolved";
    await updateSupportTicket(ticket.id, { status });
    onDialogOK(true);
  } finally {
    loading.value = false;
  }
};
</script>
