<template>
  <component :is="Teleport" to="body">
    <modal v-if="showModal" @close="closeModal">
      <template v-slot:header>
        <h3>{{ "Modifier le lieu" }}</h3>
      </template>

      <template v-slot:body>
        <div></div>
        <label>Localisation</label>
        <vue-multiselect
          v-model="location"
          :options="locations"
          :label="'name'"
          :track-by="'id'"
        ></vue-multiselect>
      </template>

      <template v-slot:footer>
        <button class="btn btn-save" @click="saveAndClose">
          {{ "Enregistrer" }}
        </button>
      </template>
    </modal>
  </component>
</template>

<script setup lang="ts">
import Modal from "../../../../../../ChillMainBundle/Resources/public/vuejs/_components/Modal.vue";
import { computed, ref } from "vue";
import { EventApi } from "@fullcalendar/core";
import { useStore } from "vuex";
import { key } from "../store";
import { Location } from "../../../../../../ChillMainBundle/Resources/public/types";
import VueMultiselect from "vue-multiselect";
//import type {Teleport} from "vue";

// see https://github.com/vuejs/core/issues/2855
import { Teleport as teleport_, TeleportProps, VNodeProps } from "vue";

const Teleport = teleport_ as new () => {
  $props: VNodeProps & TeleportProps;
};

const store = useStore(key);

const calendarRangeId = ref<number | null>(null);
const location = ref<Location | null>(null);
const showModal = ref(false);
//const tele = ref<InstanceType<typeof Teleport> | null>(null);

const locations = computed<Location[]>(() => {
  return store.state.locations.locations;
});

const startEdit = function (event: EventApi): void {
  console.log("startEditing", event);
  calendarRangeId.value = event.extendedProps.calendarRangeId;
  location.value =
    store.getters["locations/getLocationById"](
      event.extendedProps.locationId,
    ) || null;

  console.log("new location value", location.value);
  console.log("calendar range id", calendarRangeId.value);
  showModal.value = true;
};

const saveAndClose = function (e: Event): void {
  console.log("saveEditAndClose", e);

  store
    .dispatch("calendarRanges/patchRangeLocation", {
      location: location.value,
      calendarRangeId: calendarRangeId.value,
    })
    .then((_) => {
      showModal.value = false;
    });
};

const closeModal = function (_: any): void {
  showModal.value = false;
};

defineExpose({ startEdit });
</script>

<style scoped></style>
