<template>
  <div class="event-form">
    <h2>Veranstaltung Formular</h2>
    <form @submit.prevent="saveEvent">
      <table>
        <tr>
          <td><label for="name">Name:</label></td>
          <td><input type="text" id="name" v-model="eventData.name" required></td>
        </tr>
        <tr>
          <td><label for="eventType">Typ:</label></td>
          <td>
            <multiselect 
              v-model="selectedEventType" 
              :options="eventTypes" 
              label="caption" 
              track-by="id" 
              placeholder="Typ wählen"
            ></multiselect>
          </td>
        </tr>
        <tr>
          <td><label for="dateMode">Datum-Modus:</label></td>
          <td>
            <select v-model="dateMode">
              <option value="date">Datum</option>
              <option value="weekday">Wochentag</option>
              <option value="interval">Intervall</option>
            </select>
          </td>
        </tr>
        <tr v-if="dateMode === 'date' || dateMode === 'interval'">
          <td><label for="date">Datum:</label></td>
          <td><input type="date" id="date" v-model="eventData.date"></td>
        </tr>
        <tr v-if="dateMode === 'weekday' || dateMode === 'interval'">
          <td><label for="dayOfWeek">Wochentag:</label></td>
          <td>
            <multiselect 
              v-model="eventData.dayOfWeek" 
              :options="weekdays" 
              label="name" 
              track-by="value" 
              placeholder="Wochentag wählen"
            ></multiselect>
          </td>
        </tr>
        <tr>
          <td><label for="time">Uhrzeit:</label></td>
          <td><input type="time" id="time" v-model="eventData.time"></td>
        </tr>
        <tr>
          <td><label for="endTime">Ende-Uhrzeit:</label></td>
          <td><input type="time" id="endTime" v-model="eventData.endTime"></td>
        </tr>
        <tr>
          <td><label for="description">Beschreibung:</label></td>
          <td><textarea id="description" v-model="eventData.description" class="descriptionedit"></textarea></td>
        </tr>
        <tr>
          <td><label for="institution">Institution:</label></td>
          <td>
            <multiselect 
              v-model="selectedInstitution" 
              :options="localInstitutions" 
              label="name" 
              track-by="id" 
              placeholder="Institution wählen"
            ></multiselect>
          </td>
        </tr>
        <tr>
          <td><label for="eventPlace">Veranstaltungsort:</label></td>
          <td>
            <multiselect 
              v-model="selectedEventPlace" 
              :options="localEventPlaces" 
              label="name" 
              track-by="id" 
              placeholder="Veranstaltungsort wählen"
            ></multiselect>
          </td>
        </tr>
        <tr>
          <td><label for="contactPersons">Kontaktpersonen:</label></td>
          <td>
            <multiselect 
              v-model="selectedContactPersons" 
              :options="localContactPersons" 
              :multiple="true" 
              label="name" 
              track-by="id" 
              placeholder="Kontaktpersonen wählen"
            ></multiselect>
          </td>
        </tr>
        <tr>
          <td colspan="2"><button type="submit">Speichern</button></td>
        </tr>
      </table>
    </form>
  </div>
</template>

<script>
import axios from 'axios';
import Multiselect from 'vue-multiselect';

export default {
  name: 'EventForm',
  components: { Multiselect },
  props: {
    event: {
      type: Object,
      required: true,
      default: () => ({})
    },
    institutions: {
      type: Array,
      required: true,
      default: () => []
    },
    eventPlaces: {
      type: Array,
      required: true,
      default: () => []
    },
    contactPersons: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  data() {
    return {
      eventData: { ...this.event },
      selectedEventType: null,
      selectedInstitution: this.event.institution || null,
      selectedEventPlace: this.event.eventPlace || null,
      selectedContactPersons: this.event.contactPersons || [],
      eventTypes: [],
      dateMode: 'date',
      weekdays: [
        { name: 'Montag', value: 1 },
        { name: 'Dienstag', value: 2 },
        { name: 'Mittwoch', value: 3 },
        { name: 'Donnerstag', value: 4 },
        { name: 'Freitag', value: 5 },
        { name: 'Samstag', value: 6 },
        { name: 'Sonntag', value: 7 },
      ],
      localInstitutions: [...this.institutions],
      localEventPlaces: [...this.eventPlaces],
      localContactPersons: [...this.contactPersons]
    };
  },
  watch: {
    event(newVal) {
      this.eventData = { ...newVal };
      this.selectedEventType = this.eventTypes.find(type => type.id === newVal.eventTypeId) || null;
      this.selectedInstitution = newVal.institution || null;
      this.selectedEventPlace = newVal.eventPlace || null;
      this.selectedContactPersons = newVal.contactPersons || [];
      this.determineDateMode();
    },
    institutions(newVal) {
      this.localInstitutions = [...newVal];
    },
    eventPlaces(newVal) {
      this.localEventPlaces = [...newVal];
    },
    contactPersons(newVal) {
      this.localContactPersons = [...newVal];
    }
  },
  async created() {
    try {
      const eventTypeResponse = await axios.get('/event-types');
      this.eventTypes = eventTypeResponse.data;
      this.selectedEventType = this.eventTypes.find(type => type.id === this.event.eventTypeId) || null;
    } catch (error) {
      console.error('Failed to fetch event types:', error);
    }
    this.determineDateMode();
  },
  methods: {
    async saveEvent() {
      try {
        const payload = {
          ...this.eventData,
          eventTypeId: this.selectedEventType ? this.selectedEventType.id : null,
          institution_id: this.selectedInstitution ? this.selectedInstitution.id : null,
          event_place_id: this.selectedEventPlace ? this.selectedEventPlace.id : null,
          contactPersonIds: this.selectedContactPersons.map(person => person.id)
        };
        payload.dayOfWeek = payload.dayOfWeek.value;
        let response;
        if (this.eventData.id) {
          response = await axios.put(`/events/${this.eventData.id}`, payload);
        } else {
          response = await axios.post('/events', payload);
        }
        this.$emit('saved', response.data);
      } catch (error) {
        console.error('Failed to save event:', error);
      }
    },
    determineDateMode() {
      if (this.eventData.date && this.eventData.dayOfWeek) {
        this.dateMode = 'interval';
      } else if (this.eventData.date) {
        this.dateMode = 'date';
      } else if (this.eventData.dayOfWeek) {
        this.dateMode = 'weekday';
      } else {
        this.dateMode = 'date';
      }
    }
  }
};
</script>

<style scoped>
@import 'vue-multiselect/dist/vue-multiselect.css';

.event-form {
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}
table {
  width: 100%;
  border-collapse: collapse;
}
td {
  padding: 8px;
  vertical-align: top;
}
label {
  display: block;
}
button {
  margin-top: 20px;
}
.descriptionedit {
  width: 100%;
  height: 10em;
}
</style>
