<template>
  <Dialog
    dismissable-mask
    :visible="opened"
    modal
    class="max-md:w-full"
    :pt="{
      header: { style: ' display:none' },
      content: { style: 'padding: 0 !important;border-radius: 10px ' },
      root: {
        style: 'padding: 20px',
      },
    }"
  >
    <div class="flex h-full flex-col justify-between p-10">
      <div class="flex justify-end">
        <button
          class="bg-background-3 text-primary flex h-8 w-8 items-center justify-center rounded-full"
          @click="$emit('close')"
        >
          <span class="font-bold">X</span>
        </button>
      </div>
      <div class="mb-5 flex justify-center">
        <section-title class="justify-center">Terminer le trajet</section-title>
      </div>

      <Message severity="error" v-if="error">
        {{ error }}
      </Message>

      <div>
        En confirmant, vous attestez de la conformité du transport et
        autorisez<br />
        le déclenchement du processus de paiement.<br /><br />
        Cette action est irréversible.<br /><br />

        Vous serez ensuite invité à mettre en ligne votre facture.
      </div>
      <div class="align-items-center my-10 flex">
        <checkbox
          v-model="checked"
          name="checked"
          inputId="check-complete"
          :binary="true"
          class="mr-2"
        />
        <label for="check-complete">
          J'atteste que le trajet s'est déroulé conformément.</label
        >
      </div>
      <rounded-button
        @click="markReservationAsCompleted"
        :loading="loading"
        class="max-md:px-24"
        design="4"
        icon="check"
        :disabled="!checked"
      >
        Terminer ce trajet
      </rounded-button>
    </div>
  </Dialog>
</template>
<script setup>
import { defineProps, ref } from "vue";
import Dialog from "primevue/dialog";
import Checkbox from "primevue/checkbox";
import Button from "primevue/button";

const { $api, $event, $toast } = useNuxtApp();

const props = defineProps({
  opened: {
    type: Boolean,
    default: false,
  },

  reservation: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["confirm", "close"]);

const checked = ref();

const loading = ref(false);

const error = ref(null);

const markReservationAsCompleted = async () => {
  loading.value = true;
  try {
    await $api.call(
      "post",
      $api.route("reservation.completed", {
        reservation: props.reservation.id,
      })
    );

    $toast.success("Le trajet a bien été marqué comme terminé");
    $event("reservation-completed");
    emit("close");
  } catch (e) {
    $toast.error("Une erreur est survenue");
    error.value = e.response.data.message;
  } finally {
    loading.value = false;
  }
};
</script>
