<template>
  <div style="min-height: 350px">
    <div class="step_title">Indiquez votre adresse de livraison :</div>

    <div class="alert alert-warning" role="alert" v-if="alertBox === 1">
      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>

    <div class="alert alert-danger" role="alert" v-if="alertBox === 2">
      <i class="fa-solid fa-circle-exclamation"></i> Nous sommes désolé nous ne parvenons pas à géolocaliser l'adresse saisie<br/>
    </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 text-success"></i>
        <i v-else class="fa-solid fa-location-dot fa-fw text-success"></i>
      </div>
      <input type="text" placeholder="Exemple : 9 Impasse des Peupliers 13008 Marseille" class="form-control"
             v-model="query"
             @input="updateSearchResult" aria-describedby="button-addon">
      <button class="btn btn-primary" type="button" id="button-addon"
              @click="[this.currentBtSearch = 'liveSearch',checkIdAddressIsEligible()]">
        <i v-if="isChecking && currentBtSearch === 'liveSearch'" 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="step_title mt-4">Mon carnet d'adresses :</div>

    <div class="row" v-if="isConnected === false">
      <div class="col-auto">
        <a href="/cart/p/FORM_ACCESS/0/0/" class="btn btn-dark" title="S'identifier"><i
            class="fa-solid fa-user-lock me-1"></i> S'identifier <i class="fa-solid fa-angle-right ms-1"></i></a>
      </div>
    </div>

    <div v-else-if="isConnected && addressBook.length >0" class="row">
      <div v-for="(address,i) in addressBook" class="col-auto">
        <!--<i class="fa-solid fa-address-book"></i>-->
        {{ address.street }}<br/>
        {{ address.zip_code }} {{ address.city }}<br/><br/>
        <button class="btn btn-primary" type="button" @click="useAddressBook(address,i)">
          <i v-if="isChecking && currentBtSearch === 'addressBook'+i"
             class="fa-solid fa-circle-notch fa-spin fa-fw"></i>
          <i v-else class="fa-regular fa-circle-check fa-fw"></i>
          Choisir cette adresse
        </button>
      </div>

    </div>
    <div v-else-if="isConnected && addressBook.length === 0">
      Vous n'avez pas encore d'adresse enregistrée
    </div>
    <div v-else class="col-auto">
      <i class="fa-solid fa-circle-notch fa-spin fa-fw text-primary fa-2x"></i>
    </div>

  </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 alertBox = ref(0)

    const query = ref(store.fullAddress !== null ? store.fullAddress : import.meta.env.DEV ? "9 Impasse des Peupliers 13008 Marseill" : '')

    return {
      query,
      store,
      alertBox
    }
  },
  name: "address-check",
  data() {
    return {
      searchResults: [],
      isSearching: false,
      isChecking: false,
      addressBook: [],
      isConnected: null,
      currentBtSearch: null
    }
  },
  methods: {
    useAddressBook(address, i) {
      this.currentBtSearch = 'addressBook' + i

      this.store.setStreet(address.street)
      this.store.setZipCode(address.zip_code)
      this.store.setCity(address.city)
      this.checkIdAddressIsEligible()
    },
    updateSearchResult: async function () {

      this.store.setStreet(null)
      this.store.setZipCode(null)
      this.store.setCity(null)

      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 (e) {
      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

      if (import.meta.env.DEV) {
        console.log(urlApi)
      }

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


      this.isChecking = false

      if (apiResult.hasOwnProperty('address_state') && apiResult.address_state === false) {
        this.alertBox = 2
      } else if (apiResult.service_list.length > 0) {
        this.store.setProductList(apiResult.service_list);
        this.$router.push({path: '/delivery-option-step-1'});
      } else {
        this.alertBox = 1
      }

    }
  },
  async mounted() {
    let urlApi = '/php/api/v3/mmcm.php?EXEC=getAccountAddress'

    if (import.meta.env.DEV) {
      urlApi += '&ID_SESSION=U0hENaZr';
      console.log(urlApi)
    }

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

    this.isConnected = apiResult.connected

    if (apiResult.connected && apiResult.nb > 0) {
      this.addressBook = apiResult.list
    }

  }

}
</script>

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

</style>
