<template>
  <div>
    <div v-if="isOpen" class="dialog-overlay">
      <div class="dialog-content">
        <h3>Ereignisse hinzufügen</h3>
        <div>
          <label for="selection-type">Wählen Sie den Typ:</label>
          <multiselect id="selection-type" v-model="selectedTypes" :options="typeOptions" :multiple="true"
            :close-on-select="false" :clear-on-select="false" :preserve-search="true" @select="onTypeSelect" />
        </div>
        <div>
          <label><input type="checkbox" v-model="isHomepage" /> Auch Ereignisse für die Homepage zeigen</label>
        </div>
        <div v-if="selectedTypes.includes('Für bestimmte Orte')">
          <label for="places-select">Wählen Sie Orte:</label>
          <multiselect id="places-select" v-model="selectedPlaces" :options="places" :multiple="true"
            :close-on-select="false" :clear-on-select="false" :preserve-search="true" label="name" track-by="id" />
        </div>
        <div v-if="selectedTypes.includes('Für bestimmte Typen')">
          <label for="types-select">Wählen Sie Typen:</label>
          <multiselect id="types-select" v-model="selectedEventTypes" :options="eventTypes" :multiple="true"
            :close-on-select="false" :clear-on-select="false" :preserve-search="true" label="caption" track-by="id" />
        </div>
        <div v-if="selectedTypes.includes('Ein bestimmtes')">
          <label for="event-select">Wählen Sie ein Event:</label>
          <multiselect id="event-select" v-model="selectedEvent" :options="events" :multiple="false" label="name"
            track-by="id" />
        </div>
        <div>
          <label>Wählen Sie welche Elemente angezeigt werden sollen:</label>
          <div class="display-options">
            <label><input type="checkbox" v-model="displayOptions.name" /> Name</label>
            <label><input type="checkbox" v-model="displayOptions.type" /> Typ</label>
            <label><input type="checkbox" v-model="displayOptions.place" /> Ort</label>
            <label><input type="checkbox" v-model="displayOptions.description" /> Beschreibung</label>
            <label><input type="checkbox" v-model="displayOptions.time" /> Uhrzeit</label>
            <label><input type="checkbox" v-model="displayOptions.contactPerson" /> Kontaktperson</label>
            <label><input type="checkbox" v-model="displayOptions.day" /> Veranstaltungstag</label>
            <label><input type="checkbox" v-model="displayOptions.institution" /> Institution</label>
          </div>
        </div>
        <div>
          <button @click="confirmAddEventConfiguration">Bestätigen</button>
          <button @click="closeAddEventDialog">Schließen</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from '@/axios';
import Multiselect from 'vue-multiselect';

export default {
  name: 'AddEventDialog',
  components: {
    Multiselect,
  },
  emits: ['confirm'],
  setup(props, { emit }) {
    const isOpen = ref(false);
    const typeOptions = ref(['Alle', 'Für bestimmte Orte', 'Für bestimmte Typen', 'Ein bestimmtes', 'Ereignisse für Homepage']);
    const selectedTypes = ref([]);
    const places = ref([]);
    const eventTypes = ref([]);
    const events = ref([]);
    const selectedPlaces = ref([]);
    const selectedEventTypes = ref([]);
    const selectedEvent = ref(null);
    const isHomepage = ref(false);

    const displayOptions = ref({
      name: false,
      type: false,
      place: false,
      description: false,
      time: false,
      contactPerson: false,
      day: false,
      institution: false,
    });

    const openAddEventDialog = () => {
      isOpen.value = true;
      fetchPlaces();
      fetchEventTypes();
      fetchEvents();
    };

    const closeAddEventDialog = () => {
      isOpen.value = false;
    };

    const onTypeSelect = (selectedOption) => {
      if (selectedOption === 'Alle' || selectedOption === 'Ein bestimmtes') {
        selectedTypes.value = [selectedOption];
      } else {
        selectedTypes.value = selectedTypes.value.filter(option => option !== 'Alle' && option !== 'Ein bestimmtes');
      }
    };

    const confirmAddEventConfiguration = () => {
      const event = {};
      event.display = Object.keys(displayOptions.value)
        .filter(key => displayOptions.value[key]);

      if (isHomepage.value) {
        event.id = "home";
      } else if (selectedTypes.value.includes('Alle')) {
        event.id = "all"
      } else if (selectedTypes.value.includes('Ein bestimmtes')) {
        event.id = selectedEvent.value.id;
      } else {
        event.types = selectedEventTypes.value.map(eventType => eventType.id);
        event.places = selectedPlaces.value.map(place => place.id);
      }
      emit('confirm', '{{ events:' + JSON.stringify(event) + ' }}');
      closeAddEventDialog();
    };

    const fetchPlaces = async () => {
      try {
        const response = await axios.get('/event-places');
        places.value = response.data;
      } catch (error) {
        console.error('Fehler beim Laden der Orte:', error);
      }
    };

    const fetchEventTypes = async () => {
      try {
        const response = await axios.get('/event-types');
        eventTypes.value = response.data;
      } catch (error) {
        console.error('Fehler beim Laden der Typen:', error);
      }
    };

    const fetchEvents = async () => {
      try {
        const response = await axios.get('/events');
        events.value = response.data;
      } catch (error) {
        console.error('Fehler beim Laden der Events:', error);
      }
    };

    return {
      isOpen,
      typeOptions,
      selectedTypes,
      places,
      eventTypes,
      events,
      selectedPlaces,
      selectedEventTypes,
      selectedEvent,
      displayOptions,
      openAddEventDialog,
      closeAddEventDialog,
      confirmAddEventConfiguration,
      onTypeSelect,
      isHomepage,
    };
  },
};
</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.multiselect {
  width: 100%;
}

.image-block {
  display: inline-block;
  margin: 2.5px;
}

.selected {
  border: 1px solid black;
}

.display-options label {
  display:block;
}
</style>
