<template>
  <base-route-card :route="route">
    <template v-slot:footer>
      <route-card-footer-info class="mb-10" :route="route" />

      <base-route-card :route="route.reservation" v-if="route.reservation">
        <template #main>
          <price :pricing="route.reservation.pricing" />
        </template>
        <template #footer>
          <route-card-requester-footer-info
            :requester="route.reservation.requester"
            :reference="route.reservation.reference"
          />
          <div class="flex w-full items-center justify-center p-5">
            <Button
              v-if="!route.reservation.on_board"
              @click="confirmOnBoard"
              severity="success"
              icon="pi pi-check"
              label="Je confirme que le défunt est à bord du véhicule"
              outlined
              :loading="loading"
            >
            </Button>
            <Button
              v-else-if="!route.reservation.driver_end_confirmed"
              @click="modalIsOpen = true"
              severity="success"
              icon="pi pi-check"
              label="J'ai terminé ce trajet"
              outlined
            >
            </Button>
            <div v-else-if="!route.reservation.requester_end_confirmed">
              <rounded-button class="max-md:px-24" design="4" disabled>
                En attente de confirmation du demandeur
              </rounded-button>
            </div>
          </div>
          <confirm-completed-route-driver-modal
            :opened="modalIsOpen"
            :reservation="route.reservation"
            @close="modalIsOpen = false"
          />
          
        </template>
      </base-route-card>
      <message v-else severity="error" closable>
        La réservation de ce trajet est introuvable. Elle a peut-être été
        supprimée par un administrateur.
      </message>
    </template>
  </base-route-card>
</template>

<script setup>
import { ref, computed, defineProps } from "vue";

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

const { route } = defineProps({
  route: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});

const modalIsOpen = ref(false);
const loading = ref(false);

const confirmOnBoard = async () => {
  loading.value = true;
  try {
    await $api.call(
      "post",
      $api.route("reservation.onboard", {
        reservation: route.reservation.id,
      })
    );
    $toast.success("Le statut de la réservation a bien été mis à jour");
    $event("reservation-onboard");
  } catch (e) {
    $toast.error("Une erreur est survenue");
    console.error(e);
  } finally {
    loading.value = false;
  }
};
</script>
