<template>
  <div>
    <div v-if="events.length" class="mg-stack">
      <article
        v-for="event in events"
        :key="event.id"
        class="mg-card"
        :class="event.alsoOnHomepage && config.id === 'home' ? 'mg-card--highlight' : ''"
      >
        <div class="mg-card__grid" :class="{ 'mg-card__grid--no-media': !hasVisibleImage(event) }">
          <div v-if="hasVisibleImage(event)" class="mg-media" aria-hidden="true">
            <img
              :src="imageMap[event.relatedImage]"
              alt=""
              loading="lazy"
              decoding="async"
            />
          </div>

          <div>
            <h3 v-if="shouldDisplay('name')" class="mg-title">{{ event.name }}</h3>
            <p class="mg-meta">
              <span><strong>Datum:</strong> {{ formatDateOrDay(event.date, event.dayOfWeek) }}</span>
              <span v-if="shouldDisplay('time')">
                <strong>Uhrzeit:</strong>
                {{ formatTime(event.time) }}<span v-if="event.endTime"> – {{ formatTime(event.endTime) }}</span> Uhr
              </span>
              <span v-if="shouldDisplay('place') && event.eventPlace?.name">
                <strong>Ort:</strong> {{ event.eventPlace?.name }}
              </span>
            </p>

            <p v-if="shouldDisplay('description') && event.description" class="mg-text mg-accent-left">
              {{ event.description }}
            </p>

            <p v-if="shouldDisplay('contactPerson') && event.contactPersons?.length" class="mg-meta">
              <span>
                <strong>Kontakt:</strong>
                {{ event.contactPersons.map(cp => formatContactPerson(cp)).join(', ') }}
              </span>
            </p>

            <p v-if="shouldDisplay('institution') && event.institution?.name" class="mg-meta">
              <span><strong>Institution:</strong> {{ event.institution?.name }}</span>
            </p>
            <p v-if="shouldDisplay('type') && event.eventType?.caption" class="mg-meta">
              <span><strong>Typ:</strong> {{ event.eventType?.caption }}</span>
            </p>
          </div>
        </div>
      </article>
    </div>
    <p v-else>Keine Veranstaltungen verfügbar.</p>
  </div>
</template>

<script>
import axios from '@/axios';
import { format } from 'date-fns';
import { formatTime } from '@/utils/strings';

export default {
    name: 'EventRender',
    props: {
        config: {
            type: Object,
            required: true,
        }
    },
    data() {
        return {
            events: [],
            imageMap: {},
        };
    },
    async created() {
        await this.fetchEvents();
    },
    methods: {
        formatTime,
        async fetchEvents() {
            try {
                const response = await axios.post('/events/filter',
                    this.config
                );
                this.events = response.data.events;
                await Promise.all(
                    this.events
                        .filter(event => this.hasImage(event))
                        .map(async event => {
                            try {
                                const response = await axios.get('/image/' + event.relatedImage);
                                this.imageMap[event.relatedImage] = '/images/uploads/' + response.data.filename;
                            } catch (err) {
                                console.error(`Bild konnte nicht geladen werden (ID ${event.relatedImage}):`, err);
                            }
                        })
                );
            } catch (error) {
                console.error('Fehler beim Abrufen der Events', error);
            }
        },
        shouldDisplay(field) {
            return this.config.display.includes(field);
        },
        formatDateOrDay(date, dayOfWeek) {
            if (date) {
                return format(new Date(date), 'dd.MM.yyyy');
            } else if (dayOfWeek !== null && dayOfWeek !== undefined) {
                const daysOfWeek = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
                return daysOfWeek[dayOfWeek];
            }
            return '';
        },
        hasImage(event) {
            return event.relatedImage && event.relatedImage != '';
        },
        hasVisibleImage(event) {
            return this.hasImage(event) && !!this.imageMap[event.relatedImage];
        },
        async imagePath(eventImage) {
            const response = await axios.get('/image/' + eventImage);
            const path = '/images/uploads/' + response.data.filename;
            console.log(path);
            return path;
        },
        formatContactPerson(contactPerson) {
            if (!contactPerson.expiryDate) {
                return contactPerson.name;
            }
            const date = new Date(contactPerson.expiryDate);
            const formattedDate = date.toLocaleDateString('de-DE', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
            });
            return `${contactPerson.name} (bis ${formattedDate})`;
        }
    }
};
</script>

<style scoped>
.mg-title {
  margin-top: 0;
}

.mg-card__grid--no-media {
  grid-template-columns: 1fr;
}
</style>
