<template>
  <div class="step_title">Indiquez votre adresse de livraison (domicile, travail...) :</div>

  <div class="input-group mb-3">
    <div class="input-group-text">
      <i v-if="isSearching" class="fa-solid fa-circle-notch fa-spin fa-fw color-success"></i>
      <i v-else class="fa-solid fa-location-dot fa-fw color-success"></i>
    </div>
    <input type="text" placeholder="Exemple : 2 rue de la Libération 78120 Rambouillet" class="form-control"
           v-model="query"
           @input="updateSearchResult" aria-describedby="button-addon">
    <button class="btn btn-primary" type="button" id="button-addon" @click="checkIdAddressIsEligible">
      <i v-if="isChecking" class="fa-solid fa-circle-notch fa-spin fa-fw"></i>
      <i v-else class="fa-regular fa-circle-check fa-fw"></i>
      Valider
    </button>
  </div>
  <ul class="list-group">
    <li class="list-group-item text-start" v-for="(item, index) in searchResults" :key="index"
        @click="selectChoice(item)">
      {{ item.properties.label }}
    </li>
  </ul>

  <div class="alert alert-danger" role="alert" v-if="noOfferFound">
   Nous sommes désolé mais votre adresse est trop eloignée de la pharmacie pour bénéficier de ce service<br/>
   Nous vous invitions à utiliser le service de La Poste pour trouver une pharmacie proche de chez vous :
    <a href="https://www.mesmedicamentschezmoi.com" target="_blank">Accéder à mesmedicamentschezmoi.com</a>

  </div>

</template>

<script>
import {ref} from 'vue';
import {useMMCMStore} from '../stores/mmcm.js'
import {add, format} from "date-fns";


export default {
  setup() {
    const store = useMMCMStore()
    const noOfferFound = ref(false)

    return {
      store,
      noOfferFound
    }
  },
  name: "address-check",
  data() {
    return {
      query: "",
      searchResults: [],
      isSearching: false,
      isChecking: false,
    }
  },
  methods: {
    updateSearchResult: async function () {
      this.isSearching = true
      this.noOfferFound = false
      this.searchResults = await fetch('https://api-adresse.data.gouv.fr/search/?q=' + this.query)
          .then(function (response) {
            return response.json();
          }).then(function (jsonObj) {
            this.isSearching = false
            return jsonObj.features;
          }.bind(this));
    },
    selectChoice(item) {
      this.searchResults = []
      this.query = item.properties.label
      this.store.setStreet(item.properties.name)
      this.store.setZipCode(item.properties.postcode)
      this.store.setCity(item.properties.city)
    },
    checkIdAddressIsEligible: async function () {
      this.isChecking = true

      const urlApi = '/php/api/v3/mmcm.php?EXEC=getEligibility&street=' + encodeURI(this.store.street)
          + '&zip_code=' + this.store.zipCode
          + '&city=' + this.store.city


      let productList = await fetch(urlApi)
          .then(response => {
            if (response.ok) {
              return response.json();
            }
          })


      this.isChecking = false

      if (productList.length > 0) {
        this.store.setProductList(productList);
        this.$router.push({path: '/delivery-option-step-1'});
      } else {
        this.noOfferFound = true
      }


    }
  }

}
</script>

<style scoped>
.list-group li:hover {
  background-color: #d7fdc0;
  cursor: pointer;
}

</style>
