<template>
  <div>
    <div class="text-primary mb-5 text-[1.25rem] font-medium">
   
    </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="tarifData"
    >
      <Message severity="error" v-if="error">{{ error }}</Message>

      <Message :sticky="false" life="3000" severity="success" v-if="success"
        >{{ success }}
      </Message>
      <div class="grid-cols-2 gap-x-10 md:grid">
    
        <FormField
          class="flex flex-col mb-2"
          name="price_en_charge"
          label="Prise en charge HT (TVA 10%)"
        >
          <div class="p-input-icon-right">
           
            <i class="pi pi-pencil" />
           <InputNumber
              currency="EUR"
              locale="fr-FR"
              mode="currency"
              :max="99"
              v-model="tarifData.price_en_charge"
              placeholder="Prise en charge HT (TVA 10%)"
              :class="`w-full`"
              :disabled="loading"
/>
          </div>
        </FormField>

              <FormField
          class="flex flex-col mb-2"
          name="demarche_mb"
          label="FORFAIT DEMARCHE" 
        >
          <div class="p-input-icon-right">
           
            <i class="pi pi-pencil" />
           <InputNumber
              currency="EUR"
              locale="fr-FR"
              mode="currency"
              :max="99"
              v-model="tarifData.demarche_mb"
              placeholder="FORFAIT DEMARCHE"
              :class="`w-full`"
               :disabled="isDemarcheApmbLocked || loading"
/>
          </div>
        </FormField>


           <FormField
          class="flex flex-col mb-2"
          name="price_km"
          label="Prix au km HT (TVA 10%)" 
        >
          <div class="p-input-icon-right">
           
            <i class="pi pi-pencil" />
           <InputNumber
              currency="EUR"
              locale="fr-FR"
              mode="currency"
              :max="99"
              v-model="tarifData.price_km"
              placeholder="Prix au km HT (TVA 10%)"
              :class="`w-full`"
              :disabled="loading"
/>
          </div>
        </FormField>

                      <FormField
          class="flex flex-col mb-2"
          name="demarche_apmb"
          label="Forfait : Démarche après MB (TVA 20%)" style="display:none"
        >
          <div class="p-input-icon-right" style="display:none">
           
            <i class="pi pi-pencil" />
           <InputNumber
              currency="EUR"
              locale="fr-FR"
              mode="currency"
              :max="99"
              v-model="tarifData.demarche_apmb"
              placeholder="Forfait : Démarche après MB (TVA 20%)"
              :class="`w-full`"
              :disabled="isDemarcheMbLocked || loading"
/>
          </div>
        </FormField>


             
      </div>
      <div class="mb-5">
        <rounded-button
          :loading="loading"
          type="submit"
          design="1"
          class="w-full px-[5rem]"
          >{{ loading ? "Mise à jour en cours..." : "Mettre à jour" }}
        </rounded-button>

      
      </div>


    </form>
  </div>
</template>

<script setup>
import _ from "lodash";
import { ref } from "vue";



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

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

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

const emit = defineEmits(["updated"]);
const loading = ref(false);
const tarifData = ref({
   demarche_mb: 0,
  demarche_apmb: 0,
});



//const isDemarcheMbLocked = computed(() => tarifData.value.demarche_mb !== 0);
//const isDemarcheApmbLocked = computed(() => tarifData.value.demarche_apmb !== 0);





const validationErrors = ref({});

const error = ref(null);
const success = ref(null);

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

const remove = async () => {
  if (!confirm("Êtes-vous sûr de vouloir supprimer ce chauffeur ?")) {
    return;
  }

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

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

    $toast.success("Chauffeur 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 {
    await nextTick()
    if (isEdit.value) {
      console.log('yasirshah',tarifData.value)
      tarifData.value = await $api.call(
        "put",
        $api.route("me.tarif.update", { tarif: props.tarif.id }),
        tarifData.value
      );

      $toast.success("Informations du chauffeur mises à jour");
      success.value = "Informations du chauffeur mises à jour";
    } else {
    console.log(tarifData.value,'yasirshah');
      await $api.call(
        "post",
        $api.route("me.tarifs.store"),
        tarifData.value
      );

      tarifData.value = {};

      $toast.success("chauffeur ajouté avec succès");
      success.value = "chauffeur 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>
