<template>
  <div>
    <div class="text-primary mb-5 text-[1.25rem] font-medium">
      {{ isEdit ? vehicle.name : "Ajouter un véhicule" }}
    </div>
    <form
      @submit.prevent="update"
      :class="`${
        isEdit ? 'bg-background-3' : 'border-primary border-2 bg-white'
      } flex flex-col rounded-xl px-10 pb-2 pt-10`"
      v-if="vehicleData"
    >
      <Message severity="error" v-if="error">{{ error }}</Message>

      <Message :sticky="false" life="3000" severity="success" v-if="success"
        >{{ success }}
      </Message>
      <div class="mb-5">
        <FormField
          class="mb-2 w-full"
          name="name"
          label="Nom du véhicule"
          :errors="validationErrors"
        >
          <div class="p-input-icon-right">
            <i class="pi pi-pencil" />
            <InputText
              v-model="vehicleData.name"
              type="text"
              placeholder="Nom du véhicule"
              :class="`w-full ${validationErrors.name ? 'p-invalid' : ''}`"
              :disabled="loading"
            />
          </div>
        </FormField>

        <FormField
          class="mb-2 w-full"
          name="type"
          label="Type de véhicule"
          :errors="validationErrors"
        >
          <div class="p-input-icon-right">
            <i class="pi pi-pencil" />

            <Dropdown
              v-model="vehicleData.type"
              :options="typeOptions"
              optionValue="value"
              optionLabel="label"
              placeholder="Choisir un type de véhicule"
              :disabled="loading"
              :class="`w-full ${validationErrors.type ? 'p-invalid' : ''}`"
            ></Dropdown>
          </div>
        </FormField>
        <FormField
          class="mb-2 w-full"
          name="is_standard_size"
          label="Taille du véhicule"
          :errors="validationErrors"
        >
          <div class="p-input-icon-right">
            <i class="pi pi-pencil" />
            <Dropdown
              v-model="vehicleData.is_standard_size"
              :options="sizeOptions"
              optionValue="value"
              optionLabel="label"
              placeholder="Choisir une taille de véhicule"
              :disabled="loading"
              :class="`w-full ${
                validationErrors.is_standard_size ? 'p-invalid' : ''
              }`"
            ></Dropdown>
          </div>
        </FormField>
        <FormField
          class="mb-2 w-full"
          name="license_plate"
          label="Plaque d'immatriculation"
          :errors="validationErrors"
        >
          <div class="p-input-icon-right">
            <i class="pi pi-pencil" />
            <InputText
              v-model="vehicleData.license_plate"
              type="text"
              placeholder="Plaque d'immatriculation"
              :class="`w-full ${
                validationErrors.license_plate ? 'p-invalid' : ''
              }`"
              :disabled="loading"
            />
          </div>
        </FormField>
      </div>
      <div class="mb-5">
        <rounded-button
          v-if="isEdit"
          :loading="loading"
          type="submit"
          design="1"
          class="w-full px-[5rem]"
          >{{ loading ? "Mise à jour en cours..." : "Mettre à jour" }}
        </rounded-button>

        <rounded-button
          v-else
          :loading="loading"
          type="submit"
          design="1"
          class="w-full px-[5rem]"
          >{{ loading ? "Ajout en cours..." : "Ajouter le véhicule" }}
        </rounded-button>
      </div>

      <div class="flex items-center justify-end" v-if="isEdit">
        <div
          @click="remove"
          class="text-primary mb-5 cursor-pointer font-semibold transition-colors hover:text-red-500"
        >
          Supprimer le véhicule <icon icon="remove" class="ml-2 h-6 w-6"></icon>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
import _ from "lodash";

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

const props = defineProps({
  vehicle: {
    type: Object,
    default: () => ({}),
    required: false,
  },
});

const isEdit = computed(() => {
  return !!props.vehicle.id;
});

const emit = defineEmits(["updated"]);

const vehicleData = ref(null);
const validationErrors = ref({});
const loading = ref(false);
const error = ref(null);
const success = ref(null);
const typeOptions = ref([
  {
    label: "Transport avant et après mise en bière (Frigorifique)",
    value: "before_coffin",
  },
  { label: "Transport après mise en bière", value: "after_coffin" },
]);

const sizeOptions = ref([
  {
    label: "Standard: dimensions intérieures du cercueil < ou = à 195cm x 60cm",
    value: 1,
  },
  {
    label: "Hors-normes: dimensions intérieures du cercueil > à 195cm x l60cm",
    value: 0,
  },
]);

watch(
  () => props.vehicle,
  (vehicle) => {
    vehicleData.value = _.cloneDeep(vehicle);
  },
  { immediate: true }
);

const remove = async () => {
  // Ask confirmation to user with the default browser confirm dialog

  if (!confirm("Êtes-vous sûr de vouloir supprimer ce véhicule ?")) {
    return;
  }

  error.value = null;
  success.value = null;
  validationErrors.value = {};

  try {
    await $api.call(
      "delete",
      $api.route("me.vehicle.destroy", { vehicle: props.vehicle.id })
    );

    $toast.success("Véhicule supprimé avec succès");

    // Emit updated event
    emit("updated");
  } catch (e) {
    if (e.response) {
      validationErrors.value = e.response.data.errors;
      error.value = e.response.data.message;
    } else {
      error.value = "Une erreur est survenue";
    }
  } finally {
  }
};

const update = async () => {
  loading.value = true;
  error.value = null;
  success.value = null;
  validationErrors.value = {};

  try {
    if (isEdit.value) {
      vehicleData.value = await $api.call(
        "put",
        $api.route("me.vehicle.update", { vehicle: props.vehicle.id }),
        vehicleData.value
      );

      $toast.success("Informations du véhicule mises à jour");
      success.value = "Informations du véhicule mises à jour";
    } else {
      await $api.call(
        "post",
        $api.route("me.vehicles.store"),
        vehicleData.value
      );

      vehicleData.value = {};

      $toast.success("Véhicule ajouté avec succès");
      success.value = "Véhicule ajouté avec succès";
    }

    // Emit updated event

    emit("updated");
  } catch (e) {
    if (e.response) {
      if (e.response.data.message) {
        $toast.error(e.response.data.message);
        error.value = e.response.data.message;
      }

      if (e.response.status == 422) {
        if (e.response.data.errors) {
          $toast.error("Un ou plusieurs champs sont invalides");
          error.value = "Un ou plusieurs champs sont invalides";
          validationErrors.value = e.response.data.errors;
        }
      } else {
        if (e.response.data.error) {
          $toast.error(e.response.data.error);
          error.value = e.response.data.error;
        }
      }
    } else {
      error.value = e.message;
    }
  } finally {
    loading.value = false;
  }
};
</script>
