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

        <q-scroll-area class="dialog-form-scroll dialog-form-scroll--xs">
          <q-card-section class="q-pt-sm column q-gutter-y-md">
            <DefaultSelect
              v-model="resolved"
              emit-value
              label="A solicitação foi resolvida?"
              map-options
              :options="resolvedOptions"
              :rules="[inputRules.required]"
            />

            <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-scroll-area>

        <q-card-actions
          align="right"
          class="q-px-md q-pb-md"
        >
          <q-btn
            color="primary"
            label="Cancelar"
            no-caps
            outline
            @click="onDialogCancel"
          />

          <q-btn
            v-if="
              resolved !== null &&
              ticket.status === 'in_progress'
            "
            color="primary"
            label="Encerrar"
            no-caps
            :loading="loading"
            @click="onOKClick"
          />
        </q-card-actions>
      </q-card>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { updateSupportTicket } from "src/api/support_ticket";
import { useDialogPluginComponent } from "quasar";
import { useInputRules } from "src/composables/useInputRules";

import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

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

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

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

const { inputRules } = useInputRules();

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>