<template>
  <div class="vue-component">
    <h2><a id="section-40" />{{ $t("admin_location.title") }}</h2>

    <div class="mb-4">
      <label for="selectAdminLocation">
        {{ $t("admin_location.title") }}
      </label>

      <VueMultiselect
        name="selectAdminLocation"
        label="text"
        :custom-label="customLabel"
        track-by="id"
        :multiple="false"
        :searchable="true"
        :placeholder="$t('admin_location.placeholder')"
        v-model="value"
        :options="options"
        group-values="locations"
        group-label="locationCategories"
        :select-label="$t('multiselect.select_label')"
        :deselect-label="$t('multiselect.deselect_label')"
        :selected-label="$t('multiselect.selected_label')"
        @select="updateAdminLocation"
      />
    </div>

    <div v-if="!isAdminLocationValid" class="alert alert-warning to-confirm">
      {{ $t("admin_location.not_valid") }}
    </div>
  </div>
</template>

<script>
import VueMultiselect from "vue-multiselect";
import { fetchResults } from "ChillMainAssets/lib/api/apiMethods";
import { mapState, mapGetters } from "vuex";

export default {
  name: "AdminLocation",
  components: { VueMultiselect },
  data() {
    return {
      options: [],
    };
  },
  computed: {
    ...mapState({
      value: (state) => state.accompanyingCourse.administrativeLocation,
    }),
    ...mapGetters(["isAdminLocationValid"]),
  },
  mounted() {
    this.getOptions();
  },
  methods: {
    getOptions() {
      fetchResults(`/api/1.0/main/location.json`).then((response) => {
        let uniqueLocationTypeId = [
          ...new Set(response.map((o) => o.locationType.id)),
        ];
        let results = [];
        for (let id of uniqueLocationTypeId) {
          results.push({
            locationCategories: response.filter(
              (o) => o.locationType.id === id,
            )[0].locationType.title.fr,
            locations: response.filter((o) => o.locationType.id === id),
          });
        }
        this.options = results;
      });
    },
    updateAdminLocation(value) {
      this.$store
        .dispatch("updateAdminLocation", value)
        .catch(({ name, violations }) => {
          if (name === "ValidationException" || name === "AccessException") {
            violations.forEach((violation) =>
              this.$toast.open({ message: violation }),
            );
          } else {
            this.$toast.open({ message: "An error occurred" });
          }
        });
    },
    customLabel(value) {
      return value.locationType
        ? value.name
          ? `${value.name} (${value.locationType.title.fr})`
          : value.locationType.title.fr
        : "";
    },
  },
};
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
<style lang="css" scoped>
label {
  display: none;
}
</style>
