<template>
    <div class="diary">
        <h2>Trainingstagebuch</h2>
        <div>
            <label>Datum:
                <select v-model="date" @change="handleDateChange">
                    <option value="new">Neu anlegen</option>
                    <option v-for="entry in dates" :key="entry.id" :value="entry">{{ getFormattedDate(entry.date) }}
                    </option>
                </select>
            </label>
        </div>
        <div v-if="showForm && date === 'new'">
            <h3>Neues Datum anlegen</h3>
            <form @submit.prevent="createDate">
                <div>
                    <label for="newDate">Datum:</label>
                    <input type="date" id="newDate" v-model="newDate" required />
                    <button type="button" @click="setCurrentDate">Heute</button>
                </div>
                <div>
                    <label for="trainingStart">Trainingsbeginn:</label>
                    <input type="time" step="300" id="trainingStart" v-model="trainingStart" />
                </div>
                <div>
                    <label for="trainingEnd">Trainingsende:</label>
                    <input type="time" step="300" id="trainingEnd" v-model="trainingEnd" />
                </div>
                <button type="submit">Datum anlegen</button>
            </form>
        </div>

        <div v-if="!showForm && date !== null && date !== 'new'">
            <h3>Trainingszeiten bearbeiten <span @click="toggleShowGeneralData" class="clickable">{{ showGeneralData ?
                    '-' : '+' }}</span></h3>
            <form @submit.prevent="updateTrainingTimes" v-if="showGeneralData">
                <div>
                    <label for="editTrainingStart">Trainingsbeginn:</label>
                    <input type="time" step="300" id="editTrainingStart" v-model="trainingStart" />
                </div>
                <div>
                    <label for="editTrainingEnd">Trainingsende:</label>
                    <input type="time" step="300" id="editTrainingEnd" v-model="trainingEnd" />
                </div>
                <button type="submit">Zeiten aktualisieren</button>
            </form>
        </div>
        <div v-if="date !== 'new' && date !== null" style="overflow:hidden">
            <div class="columns">
                <div class="column">
                    <h3 v-if="showGeneralData">Gruppenverwaltung</h3>
                    <div v-if="showGeneralData">
                        <h4>Vorhandene Gruppen</h4>
                        <ul>
                            <li v-for="group in groups" :key="group.id">
                                <span v-if="editingGroupId !== group.id" @click="editGroup(group.id)">{{ group.name
                                    }}</span>
                                <input v-else type="text" v-model="group.name" @blur="saveGroup(group)"
                                    @keyup.enter="saveGroup(group)" @keyup.esc="cancelEditGroup"
                                    style="display: inline;width:10em" />
                                <span v-if="editingGroupId !== group.id" @click="editGroup(group.id)"> (Leiter: {{
                                    group.lead }}) </span>
                                <input v-else type="text" v-model="group.lead" @blur="saveGroup(group)"
                                    @keyup.enter="saveGroup(group)" @keyup.esc="cancelEditGroup"
                                    style="display: inline;width:10em" />
                            </li>
                        </ul>
                    </div>
                    <div v-if="showGeneralData">
                        <h4>Neue Gruppe erstellen</h4>
                        <div class="groups">
                            <div>
                                <label for="groupName">Gruppenname:</label>
                                <input type="text" v-model="newGroupName" required />
                            </div>
                            <div>
                                <label for="groupLead">Leiter:</label>
                                <input type="text" v-model="newGroupLead" required />
                            </div>
                            <div>
                                <label>&nbsp;</label>
                                <button type="submit" @click="addGroup">Gruppe hinzufügen</button>
                            </div>
                        </div>
                    </div>
                    <h3>Trainingsplan</h3>
                    <div style="overflow: auto;">
                        <table>
                            <thead>
                                <tr>
                                    <th>Startzeit</th>
                                    <th>Aktivität / Zeitblock</th>
                                    <th>Gruppe</th>
                                    <th>Dauer (Min)</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody ref="sortableList">
                                <template v-for="(item, index) in trainingPlan" :key="item.id">
                                    <tr>
                                        <td>{{ item.startTime }}</td>
                                        <td>
                                            <span v-if="item.isTimeblock"><i>Zeitblock</i></span>
                                            <span v-else>{{ item.predefinedActivity ? item.predefinedActivity.name :
                                                item.activity }}</span>
                                        </td>
                                        <td>{{ item.groupActivity ? item.groupActivity.name : '' }}</td>
                                        <td><span v-if="item.durationText">{{ item.durationText }} / </span>{{
                                            item.duration }}</td>
                                        <td><button @click="removePlanItem(item.id)">Entfernen</button></td>
                                    </tr>
                                    <template v-for="groupItem in item.groupActivities">
                                        <tr>
                                            <td></td>
                                            <td>{{ groupItem.groupPredefinedActivity.name }}</td>
                                            <td>{{ groupItem.groupsGroupActivity.name }}</td>
                                            <td></td>
                                            <td></td>
                                        </tr>
                                    </template>
                                </template>
                                <tr>
                                    <td>{{ calculateNextTime }}</td>
                                    <td colspan="4" v-if="!addNewItem && !addNewTimeblock && !addNewGroupActivity">
                                        <button @click="openNewPlanItem()">Gesamt-Aktivität</button>
                                        <button @click="addTimeblock()">Zeitblock</button>
                                        <button v-if="parentIsTimeblock()"
                                            @click="addGroupActivity">Gruppen-Aktivität</button>
                                    </td>
                                    <td v-if="addNewItem || addNewGroupActivity">
                                        <input v-if="addtype === 'activity'" type="text" v-model="newPlanItem.activity"
                                            placeholder="Aktivität / Zeitblock" required />
                                    </td>
                                    <td v-else-if="addNewTimeblock">Zeitblock</td>
                                    <td v-if="addNewGroupActivity" colspan="2">
                                        <select v-model="newPlanItem.groupId">
                                            <option v-for="group in groups" :key="group.id" :value="group.id">{{
                                                group.name }}</option>
                                        </select>
                                    </td>
                                    <td v-else-if="addNewItem || addNewTimeblock"></td>
                                    <td v-if="(addNewItem || addNewTimeblock) && !addNewGroupActivity">
                                        <input type="text" v-model="newPlanItem.durationInput"
                                            @input="calculateDuration" placeholder="z.B. 2x7 oder 3*5"
                                            style="width:10em" />
                                        <input type="number" v-model="newPlanItem.duration" placeholder="Minuten" />
                                    </td>
                                    <td v-else-if="addNewGroupActivity"></td>
                                    <td v-if="addNewItem || addNewTimeblock || addNewGroupActivity">
                                        <span class="add-plan-item" @click="addPlanItem">+</span>
                                        <span class="cancel" @click="cancelAddItem">X</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <button v-if="trainingPlan && trainingPlan.length && trainingPlan.length > 0"
                            @click="generatePDF">Als PDF herunterladen</button>
                    </div>
                </div>
                <div class="column">
                    <h3>Aktivitäten</h3>
                    <textarea v-model="newActivity"></textarea>
                    <button @click="addActivity">Aktivität hinzufügen</button>
                    <ul>
                        <li v-for="activity in activities" :key="activity.id">
                            {{ activity.description }}
                        </li>
                    </ul>
                    <multiselect v-model="selectedActivityTags" :options="availableTags" placeholder="Tags auswählen"
                        label="name" track-by="id" multiple :close-on-select="true" @tag="addNewTag"
                        @remove="removeActivityTag" :allow-empty="false" @keydown.enter.prevent="addNewTagFromInput" />
                    <h3>Teilnehmer</h3>
                    <ul>
                        <li v-for="member in sortedMembers()" :key="member.id">
                            <input type="checkbox" :value="member.id" @change="toggleParticipant(member.id)"
                                :checked="isParticipant(member.id)">
                            <span class="clickable" @click="selectMember(member)"
                                :class="{ highlighted: selectedMember && selectedMember.id === member.id }">{{
                                member.firstName
                                }} {{
                                member.lastName }}</span>
                            <span v-if="false" @click="openNotesModal(member)" class="clickable">📝</span>
                            <span @click="showPic(member)" class="img-icon" v-if="member.hasImage">&#x1F5BC;</span>
                            <span class="pointer" @click="openTagInfos(member)">ℹ️</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <div v-if="showTagHistoryModal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeTagHistoryModal">&times;</span>
                <h3>Tag-Historie {{ tagHistoryMember.firstName }} {{ tagHistoryMember.lastName }}</h3>
                <div>
                    <multiselect v-model="selectedMemberDayTags" :options="selectedActivityTags"
                        placeholder="Tags auswählen" label="name" track-by="id" multiple :close-on-select="false"
                        :taggable="false" @select="addNewTagForDay" :allow-empty="false" />
                </div>
                <div v-if="tagHistory">
                    <div v-for="tag in tagHistory" :key="tag.id">
                        <div class="tag-headerplement">{{ tag.name }}</div>
                        <ul class="tag-list">
                            <li v-for="entry in tag.diaryMemberTags" :key="entry.id">{{
                                getFormattedDate(entry.diaryDates.date) }}</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="showNotesModal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeNotesModal">&times;</span>
                <h3>Notizen für {{ noteMember.firstName }} {{ noteMember.lastName }}</h3>
                <div>Telefon-Nr.: {{ noteMember.phone }}</div>
                <div class="modal-body">
                    <div class="modal-left">
                        <img v-if="noteMember.imageUrl" :src="noteMember.imageUrl" alt="Mitgliedsbild"
                            style="width: 250px; height: 250px; object-fit: cover;" />
                    </div>
                    <div class="modal-right">
                        <multiselect v-model="selectedMemberTags" :options="availableTags" placeholder="Tags auswählen"
                            label="name" track-by="id" multiple :close-on-select="false"
                            @tag="addNewTagForMemberFromSelection" @remove="removeMemberDayTag" allow-empty="false" />
                        <div>
                            <textarea v-model="newNoteContent" placeholder="Neue Notiz" rows="4" cols="30"></textarea>
                            <button @click="addMemberNote">Hinzufügen</button>
                        </div>
                        <ul>
                            <li v-for="note in notes" :key="note.id">
                                <button @click="deleteNote(note.id)" class="cancel-action">Löschen</button>
                                {{ note.content }}
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div v-if="showImage" class="memberImage">
            <img :src="imageUrl" @click="closeImage" />
        </div>
    </div>
    <img v-if="showImage" class="img" :src="imageUrl" @click="closeImage()" />
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import Multiselect from 'vue-multiselect';
import Sortable from 'sortablejs';
import PDFGenerator from '../components/PDFGenerator.js';

export default {
    name: 'DiaryView',
    components: { Multiselect },
    data() {
        return {
            date: null,
            dates: [],
            showForm: false,
            newDate: '',
            trainingStart: '',
            trainingEnd: '',
            members: [],
            participants: [],
            newActivity: '',
            activities: [],
            notes: [],
            newNoteContent: '',
            noteMember: null,
            selectedMember: null,
            showNotesModal: false,
            selectedActivityTags: [],
            selectedMemberTags: [],
            selectedMemberDayTags: [],
            availableTags: [],
            previousActivityTags: [],
            previousMemberTags: [],
            trainingPlan: [],
            newPlanItem: {
                activity: '',
                duration: '',
                durationText: '',
                groupId: '',
                isTimeBlock: false,
            },
            predefinedActivities: [],
            showDropdown: false,
            showImage: false,
            imageUrl: '',
            groups: [],
            currentTimeBlockId: null,
            newGroupName: '',
            newGroupLead: '',
            addtype: 'activity',
            addNewItem: false,
            addNewGroupActivity: false,
            addNewTimeblock: false,
            showGeneralData: false,
            editingGroupId: null,
            doMemberTagUpdates: true,
            showTagHistoryModal: false,
            tagHistoryMember: null,
            tagHistory: null,
            intermediateTimes: [],
            bellSound: new Audio('/sound/bell-123742.mp3'),
            thumbSound: new Audio('/sound/thump-105302.mp3'),
            timeChecker: null,
        };
    },
    watch: {
        selectedMemberTags(newTags) {
            this.updateMemberTags(newTags);
        },
        selectedActivityTags(newTags) {
            this.updateActivityTags(newTags);
        },
    },
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub', 'currentClubName']),
        calculateNextTime() {
            this.calculateAllItemTimes();
            if (this.trainingPlan.length === 0) {
                return this.trainingStart;
            }
            const lastItem = this.trainingPlan[this.trainingPlan.length - 1];
            return lastItem.endTime;
        },
        filteredPredefinedActivities() {
            const input = this.newPlanItem.activity.toLowerCase();
            return this.predefinedActivities.filter(activity =>
                activity.name.toLowerCase().includes(input)
            );
        },
    },
    methods: {
        async init() {
            if (this.isAuthenticated && this.currentClub) {
                const response = await apiClient.get(`/diary/${this.currentClub}`);
                this.dates = response.data.map(entry => ({ id: entry.id, date: entry.date }));
                await this.loadTags();
                await this.loadPredefinedActivities();
            }
        },
        setCurrentDate() {
            const today = new Date().toISOString().split('T')[0];
            this.newDate = today;
        },
        async handleDateChange() {
            this.showForm = this.date === 'new';
            if (this.date && this.date !== 'new') {
                const dateId = this.date.id;
                const response = await apiClient.get(`/diary/${this.currentClub}`);
                const dateData = response.data.find(entry => entry.id === dateId);
                this.trainingStart = dateData.trainingStart;
                this.trainingEnd = dateData.trainingEnd;
                this.selectedActivityTags = dateData.diaryTags.map(tag => ({
                    id: tag.id,
                    name: tag.name
                }));
                this.previousActivityTags = [...this.selectedActivityTags];
                await this.loadMembers();
                await this.loadParticipants(dateId);
                await this.loadActivities(dateId);
                this.trainingPlan = await apiClient
                    .get(`/diary-date-activities/${this.currentClub}/${this.date.id}`)
                    .then(response => response.data);
                this.calculateIntermediateTimes();
                this.initializeSortable();
                await this.loadGroups();
                this.showGeneralData = false;
                this.startCheckingTime();
            } else {
                this.newDate = '';
                this.trainingStart = '';
                this.trainingEnd = '';
                this.participants = [];
            }
        },
        initializeSortable() {
            const el = this.$refs.sortableList;
            Sortable.create(el, {
                handle: ".drag-handle",
                onEnd: this.onDragEnd,
            });
        },
        async createDate() {
            try {
                const response = await apiClient.post(`/diary/${this.currentClub}`, {
                    date: this.newDate,
                    trainingStart: this.trainingStart || null,
                    trainingEnd: this.trainingEnd || null,
                });
                this.dates.push({ id: response.data.id, date: response.data.date });
                this.date = { id: response.data.id, date: response.data.date };
                this.showForm = false;
                this.newDate = '';
                this.trainingStart = response.data.trainingStart;
                this.trainingEnd = response.data.trainingEnd;
            } catch (error) {
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async updateTrainingTimes() {
            try {
                const dateId = this.date.id;
                await apiClient.put(`/diary/${this.currentClub}`, {
                    dateId,
                    trainingStart: this.trainingStart || null,
                    trainingEnd: this.trainingEnd || null,
                });
                alert('Trainingszeiten erfolgreich aktualisiert.');
            } catch (error) {
                console.error('Fehler beim Aktualisieren der Trainingszeiten:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async loadMembers() {
            const response = await apiClient.get(`/clubmembers/get/${this.currentClub}/false`);
            this.members = response.data;
        },
        async loadParticipants(dateId) {
            const response = await apiClient.get(`/participants/${dateId}`);
            this.participants = response.data.map(participant => participant.memberId);
        },
        async loadActivities(dateId) {
            const response = await apiClient.get(`/activities/${dateId}`);
            this.activities = response.data;
        },
        async loadTags() {
            const response = await apiClient.get('/tags');
            this.availableTags = response.data;
        },
        async loadPredefinedActivities() {
            try {
                const response = await apiClient.get('/predefined-activities');
                this.predefinedActivities = response.data;
            } catch (error) {
                console.error('Fehler beim Laden der vordefinierten Aktivitäten:', error);
            }
        },
        async loadGroups() {
            try {
                const response = await apiClient.get(`/group/${this.currentClub}/${this.date.id}`);
                this.groups = response.data;
            } catch (error) {
                console.log(error);
            }
        },
        isParticipant(memberId) {
            return this.participants.includes(memberId);
        },
        async toggleParticipant(memberId) {
            const isParticipant = this.isParticipant(memberId);
            const dateId = this.date.id;
            if (isParticipant) {
                await apiClient.post('/participants/remove', {
                    diaryDateId: dateId,
                    memberId
                });
                this.participants = this.participants.filter(id => id !== memberId);
            } else {
                await apiClient.post('/participants/add', {
                    diaryDateId: dateId,
                    memberId
                });
                this.participants.push(memberId);
            }
        },
        async addActivity() {
            const dateId = this.date.id;
            if (this.newActivity) {
                const response = await apiClient.post('/activities/add', {
                    diaryDateId: dateId,
                    description: this.newActivity,
                    tags: this.selectedActivityTags.map(tag => tag.id)
                });
                this.activities.push(response.data[0]);
                this.newActivity = '';
                this.selectedActivityTags = [];
            }
        },
        async selectMember(member) {
            this.selectedMember = member;
        },
        async openNotesModal(member) {
            this.noteMember = member;
            this.loadMemberNotesAndTags(this.date.id, member.id);
            this.showNotesModal = true;
        },
        async loadMemberNotesAndTags(diaryDateId, memberId) {
            this.doMemberTagUpdates = false;
            try {
                const notesResponse = await apiClient.get(`/diarymember/${this.currentClub}/note`, {
                    params: { diaryDateId, memberId }
                });
                this.notes = notesResponse.data;
                const tagsResponse = await apiClient.get(`/diarymember/${this.currentClub}/tag`, {
                    params: { diaryDateId, memberId }
                });
                this.selectedMemberTags = tagsResponse.data.map(tag => ({
                    id: tag.tag.id,
                    label: tag.tag.label
                }));
            } catch (error) {
                console.error('Error loading member notes and tags:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
            this.doMemberTagUpdates = true;
        },
        async addMemberNote() {
            if (this.newNoteContent && this.selectedMember) {
                const response = await apiClient.post(`/diarymember/${this.currentClub}/note`, {
                    memberId: this.selectedMember.id,
                    diaryDateId: this.date.id,
                    content: this.newNoteContent
                });
                this.notes = response.data;
                this.newNoteContent = '';
                this.selectedTagsNotes = [];
            } else {
                alert('Bitte wählen Sie einen Teilnehmer aus und geben Sie einen Notiztext ein.');
            }
        },
        async deleteNote(noteId) {
            const response = await apiClient.delete(`/diarymember/${this.currentClub}/note/${noteId}`, {
                clubId: this.currentClub
            });
            this.notes = response.data;
        },
        closeNotesModal() {
            this.showNotesModal = false;
        },
        async addNewTagFromInput(event) {
            const inputValue = event.target.value.trim();
            if (inputValue) {
                await this.addNewTag(inputValue);
            }
        },
        async addNewTag(newTagName) {
            try {
                const response = await apiClient.post('/tags', { name: newTagName });
                const newTag = response.data[0];
                this.availableTags.push(newTag);
                this.selectedActivityTags.push(newTag);
            } catch (error) {
                console.error('Fehler beim Hinzufügen eines neuen Tags:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async addNewTagForMemberFromInput(event) {
            const inputValue = event.target.value.trim();
            if (inputValue) {
                await this.addNewTagForMember(inputValue);
            }
        },
        async addNewTagForMember(newTagName) {
            try {
                const response = await apiClient.post('/tags', { name: newTagName });
                const newTag = response.data;
                this.availableTags.push(newTag);
                this.selectedMemberTags.push(newTag);
                await this.linkTagToMemberAndDate(newTag);
            } catch (error) {
                console.error('Fehler beim Hinzufügen eines neuen Tags für das Mitglied:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async linkTagToDiaryDate(tag) {
            if (!tag || !tag.id) {
                console.warn("Ungültiges Tag-Objekt:", tag);
                return;
            }
            try {
                const tagId = tag.id;
                const response = await apiClient.post(`/diary/tag/${this.currentClub}/add-tag`, {
                    diaryDateId: this.date.id,
                    tagId: tagId
                });
            } catch (error) {
                console.error('Fehler beim Verknüpfen des Tags mit dem Trainingstag:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async linkTagToMemberAndDate(tag) {
            try {
                const tagId = tag.id;
                await apiClient.post(`/diarymember/${this.currentClub}/tag`, {
                    diaryDateId: this.date.id,
                    memberId: this.selectedMember.id,
                    tagId: tagId
                });
            } catch (error) {
                console.error('Fehler beim Verknüpfen des Tags mit dem Mitglied und Datum:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async updateActivityTags() {
            try {
                const selectedTags = this.selectedActivityTags;
                if (!Array.isArray(selectedTags)) {
                    throw new TypeError('Expected selectedTags to be an array');
                }
                for (let tag of selectedTags) {
                    if (tag && tag.id && !this.previousActivityTags.some(prevTag => prevTag.id === tag.id)) {
                        await this.linkTagToDiaryDate(tag);
                    }
                }
                this.previousActivityTags = [...selectedTags];
            } catch (error) {
                console.error('Fehler beim Verknüpfen der Tags mit dem Trainingstag:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async updateMemberTags() {
            if (!this.doMemberTagUpdates || !this.selectedMember) {
                return;
            }
            try {
                for (let tag of this.selectedMemberTags) {
                    if (!this.previousMemberTags.includes(tag)) {
                        await this.linkTagToMemberAndDate(tag);
                    }
                }
                this.previousMemberTags = [...this.selectedMemberTags];
            } catch (error) {
                console.error('Fehler beim Verknüpfen der Tags mit dem Mitglied und Datum:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async removeMemberTag(tagId) {
            try {
                await apiClient.post(`/diarymember/${this.currentClub}/tag/remove`, {
                    diaryDateId: this.date.id,
                    memberId: this.selectedMember.id,
                    tagId: tagId
                });
                this.selectedMemberTags = this.selectedMemberTags.filter(tag => tag.id !== tagId);
            } catch (error) {
                console.error('Fehler beim Entfernen des Tags:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async removeMemberNote(noteContent) {
            try {
                await apiClient.post(`/diarymember/${this.currentClub}/note/remove`, {
                    diaryDateId: this.date.id,
                    memberId: this.selectedMember.id,
                    content: noteContent
                });
                this.notes = this.notes.filter(note => note.content !== noteContent);
            } catch (error) {
                console.error('Fehler beim Entfernen der Notiz:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async removeActivityTag(tag) {
            try {
                const tagId = tag.id;
                await apiClient.delete(`/diary/${this.currentClub}/tag`, {
                    params: { tagId }
                });
                this.selectedActivityTags = this.selectedActivityTags.filter(t => t.id !== tagId);
            } catch (error) {
                console.error('Fehler beim Entfernen des Tags:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async handleActivityTagInput(tags) {
            const newTags = tags.filter(tag => !this.previousActivityTags.some(prevTag => prevTag.id === tag.id));
            for (const tag of newTags) {
                await this.linkTagToDiaryDate(tag);
            }
            this.previousActivityTags = [...tags];
        },
        selectPredefinedActivity(activity) {
            this.newPlanItem.activity = activity.name;
            this.newPlanItem.durationText = activity.durationText;
            this.newPlanItem.duration = activity.duration || '';
            this.showDropdown = false;
        },
        async addPlanItem() {
            try {
                if (this.addNewItem || this.addNewTimeblock) {
                    await apiClient.post(`/diary-date-activities/${this.currentClub}`, {
                        diaryDateId: this.date.id,
                        activity: this.addNewTimeblock ? '' : this.newPlanItem.activity,
                        isTimeblock: this.addNewTimeblock,
                        duration: this.newPlanItem.duration,
                        durationText: this.newPlanItem.durationText,
                        orderId: this.trainingPlan.length
                    });
                } else if (this.addNewGroupActivity) {
                    await apiClient.post(`/diary-date-activities/group`, {
                        clubId: this.currentClub,
                        diaryDateId: this.date.id,
                        activity: this.newPlanItem.activity,
                        groupId: this.newPlanItem.groupId,
                    });
                }
                this.addNewTimeblock = false;
                this.addNewItem = false;
                this.addNewGroupActivity = false;
                this.newPlanItem = { activity: '', duration: '', durationText: '', groupId: '' };
                this.trainingPlan = await apiClient.get(`/diary-date-activities/${this.currentClub}/${this.date.id}`).then(response => response.data);
                this.calculateIntermediateTimes();
            } catch (error) {
                console.error('Fehler beim Hinzufügen des Planungsitems:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async updatePlanItemGroup(planItemId, groupId) {
            try {
                await apiClient.put(`/diary-date-activities/${this.currentClub}/${planItemId}/group`, {
                    groupId: groupId
                });
                this.calculateIntermediateTimes();
            } catch (error) {
                console.error('Fehler beim Aktualisieren der Planungs-Item-Gruppe:', error);
            }
        },
        async removePlanItem(planItemId) {
            try {
                await apiClient.delete(`/diary-date-activities/${this.currentClub}/${planItemId}`);
                this.trainingPlan = this.trainingPlan.filter(item => item.id !== planItemId);
                this.calculateIntermediateTimes();
            } catch (error) {
                console.error('Fehler beim Entfernen des Planungsitems:', error);
            }
        },

        isTimeGreater(time1, time2) {
            const [hours1, minutes1] = time1.split(':').map(Number);
            const [hours2, minutes2] = time2.split(':').map(Number);

            if (hours1 > hours2) return true;
            if (hours1 < hours2) return false;
            return minutes1 > minutes2;
        },
        calculateAllItemTimes() {
            let currentTime = this.trainingStart;
            let index = 0;
            const trainingPlanLength = this.trainingPlan.length;

            while (index < trainingPlanLength) {
                const currentItem = this.trainingPlan[index];

                if (!currentItem.groupId) {
                    currentItem.startTime = currentTime;
                    currentItem.endTime = this.addDurationToTime(currentItem.startTime, currentItem.duration);
                    currentTime = currentItem.endTime;
                    index += 1;
                } else {
                    const groupActivities = [];
                    while (index < trainingPlanLength && this.trainingPlan[index].groupId) {
                        groupActivities.push(this.trainingPlan[index]);
                        index += 1;
                    }
                    for (const item of groupActivities) {
                        item.startTime = currentTime;
                        item.endTime = this.addDurationToTime(item.startTime, item.duration);
                    }
                    let latestEndTime = currentTime;
                    for (const item of groupActivities) {
                        if (this.isTimeGreater(item.endTime, latestEndTime)) {
                            latestEndTime = item.endTime;
                        }
                    }
                    currentTime = latestEndTime;
                }
            }
        },

        calculatePlanItemTime(index) {
            this.calculateAllItemTimes();
            return this.trainingPlan[index].startTime;
        },
        addDurationToTime(startTime, duration) {
            let [hours, minutes] = startTime.split(':').map(Number);
            minutes += Number(duration);
            if (minutes >= 60) {
                hours += Math.floor(minutes / 60);
                minutes = minutes % 60;
            }
            hours = hours % 24;
            return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
        },
        calculateDuration() {
            const input = this.newPlanItem.durationInput;
            let calculatedDuration = 0;
            const multiplyPattern = /(\d+)\s*[x*]\s*(\d+)/i;
            const match = input.match(multiplyPattern);
            if (match) {
                const [, num1, num2] = match;
                calculatedDuration = parseInt(num1) * parseInt(num2);
            } else if (!isNaN(input)) {
                calculatedDuration = parseInt(input);
            }
            calculatedDuration = Math.ceil(calculatedDuration / 5) * 5;
            if (!this.newPlanItem.durationText || this.newPlanItem.durationText === input) {
                this.newPlanItem.duration = calculatedDuration;
                this.newPlanItem = { ...this.newPlanItem, duration: calculatedDuration };
            }
        },
        async removePlanItem(planItemId) {
            try {
                await apiClient.delete(`/diary-date-activities/${this.currentClub}/${planItemId}`);
                this.trainingPlan = this.trainingPlan.filter(item => item.id !== planItemId);
            } catch (error) {
                console.error('Fehler beim Entfernen des Planungsitems:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async onDragEnd(evt) {
            const movedItem = this.trainingPlan[evt.oldIndex];
            try {
                await apiClient.put(`/diary-date-activities/${this.currentClub}/${movedItem.id}/order`, {
                    orderId: evt.newIndex
                });
                this.recalculateTimes();
            } catch (error) {
                console.error('Fehler beim Aktualisieren der Reihenfolge:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
/*        async loadMemberImage(member) {
            try {
                const response = await apiClient.get(`/clubmembers/image/${this.currentClub}/${member.id}`, {
                    responseType: 'blob',
                });
                const imageUrl = URL.createObjectURL(response.data);
                member.imageUrl = imageUrl;
            } catch (error) {
                member.imageUrl = null;
            }
        },*/
        async generatePDF() {
            const pdf = new PDFGenerator();
            pdf.addTrainingPlan(this.currentClubName, this.date.date, this.trainingStart, this.trainingEnd, this.trainingPlan);
            pdf.save('trainingsplan.pdf');
        },
        sortedMembers() {
            return this.members.sort((a, b) => {
                const firstNameComparison = a.firstName.localeCompare(b.firstName);
                if (firstNameComparison === 0) {
                    return a.lastName.localeCompare(b.lastName);
                }
                return firstNameComparison;
            });
        },
        async showPic(member) {
            this.loadMemberImage(member);
            this.showImage = true;
        },
        closeImage() {
            this.showImage = false;
            this.imageUrl = '';
        },
        async loadMemberImage(member) {
            try {
                const response = await apiClient.get(`/clubmembers/image/${this.currentClub}/${member.id}`, {
                    responseType: 'blob',
                });
                this.imageUrl = URL.createObjectURL(response.data);
                this.showImage = true;
            } catch (error) {
                this.imageUrl = null;
            }
        },
        recalculateTimes() {
            let currentTime = this.trainingStart;
            this.trainingPlan.forEach((item, index) => {
                item.startTime = currentTime;
                currentTime = this.addDurationToTime(currentTime, item.duration);
            });
        },
        async addGroup() {
            try {
                const form = {
                    clubid: this.currentClub,
                    dateid: this.date.id,
                    name: this.newGroupName,
                    lead: this.newGroupLead,
                }
                await apiClient.post('/group', form);
                await this.loadGroups();
            } catch (error) {

            }
        },
        parentIsTimeblock() {
            return this.trainingPlan && this.trainingPlan.length > 0 ? (this.trainingPlan[this.trainingPlan.length - 1].isTimeblock) : false;
        },
        openNewPlanItem() {
            this.addNewItem = true;
            this.addNewGroupActivity = false;
            this.addNewTimeblock = false;
        },
        cancelAddItem() {
            this.addNewItem = false;
            this.addNewGroupActivity = false;
            this.addNewTimeblock = false;
        },
        addTimeblock() {
            this.addNewTimeblock = true;
            this.addNewGroupActivity = false;
            this.addNewItem = false;
        },
        async addGroupActivity() {
            this.addNewGroupActivity = true;
            this.addNewItem = false;
            this.addNewTimeblock = false;
        },
        toggleShowGeneralData() {
            this.showGeneralData = !this.showGeneralData;
        },
        getFormattedDate(date) {
            return (new Date(date)).toLocaleDateString('de-DE', { year: 'numeric', month: '2-digit', day: '2-digit'});
        },
        editGroup(groupId) {
            this.editingGroupId = groupId;
        },
        async saveGroup(group) {
            try {
                await apiClient.put(`/group/${group.id}`, {
                    name: group.name,
                    lead: group.lead,
                    clubid: this.currentClub,
                    dateid: this.date.id,
                });
                this.editingGroupId = null; 
            } catch (error) {
                console.error('Fehler beim Speichern der Gruppendaten:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        cancelEditGroup() {
            this.editingGroupId = null; 
        },
        async openTagInfos(member) {
            if (!member) {
                console.warn("Member is undefined or null");
                return;
            }
            this.showTagHistoryModal = true;
            this.tagHistoryMember = member;
            const tags = await apiClient.get(`/diarydatetags/${this.currentClub}/${member.id}`);
            this.tagHistory = tags.data;
            this.selectedMemberDayTags = [];
            this.selectedMemberDayTags = this.tagHistory.filter(tag => {
                return tag.diaryMemberTags.some(memberTag =>
                    memberTag.diaryDates && memberTag.diaryDates.id === this.date.id
                );
            });
        },
        closeTagHistoryModal() {
            this.showTagHistoryModal = false;
            this.tagHistoryMember = null;
        },
        async addNewTagForDay(tag) {
            await apiClient.post(`/diarydatetags/${this.currentClub}`, {
                dateId:this.date.id,
                memberId: this.tagHistoryMember.id,
                tag: tag,
            });
        },
        async removeDayTag(tag) {
        },
        async addNewDayTagFromInput(event) {
            const tag = event.target.value;
            if (tag) {
                await this.addNewTagForDay(tag);
            }
        },

        startCheckingTime() {
            if (this.timeChecker) clearInterval(this.timeChecker);
            this.timeChecker = setInterval(() => {
                const currentTime = new Date().toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                if (!this.trainingStart || ! this.trainingEnd) {
                    return;
                }
                let startCheckTime = this.trainingStart;
                let endCheckTime = this.trainingEnd;
                const startCheckTimeBlocks = startCheckTime.split(':');
                if (startCheckTimeBlocks.length < 3) {
                    startCheckTime = `${startCheckTime}:00`;
                }
                const endCheckTimeBlocks = endCheckTime.split(':');
                if (endCheckTimeBlocks.length < 3) {
                    endCheckTime = `${endCheckTime}:00`;
                }
                if (startCheckTime && currentTime === startCheckTime) {
                    this.playBellSound();
                }
                if (endCheckTime && currentTime === endCheckTime) {
                    this.playBellSound();
                }
                if (this.intermediateTimes.includes(currentTime)) {
                    this.playThumbSound();
                }
            }, 1000);
        },

        playBellSound() {
            this.bellSound.play()
                .then(() => {
                    console.log("Bell sound played successfully");
                })
                .catch(error => {
                    console.error("Error playing bell sound:", error);
                });
        },

        playThumbSound() {
            this.thumbSound.play()
                .then(() => {
                    console.log("Thumb sound played successfully");
                })
                .catch(error => {
                    console.error("Error playing thumb sound:", error);
                });
        },

        calculateIntermediateTimes() {
            if (!this.trainingPlan || this.trainingPlan.length === 0) {
                this.intermediateTimes = [];
                return;
            }
            let times = [];
            let currentTime = new Date("2025-01-01 " + this.trainingStart);
            this.trainingPlan.forEach(item => {
                const rawItem = JSON.parse(JSON.stringify(item)); 
                currentTime.setMinutes(currentTime.getMinutes() + item.duration);
                times.push(currentTime.toTimeString({ hours: '2-digit', minutes: '2-digit', seconds: '2-digit' }).slice(0, 8));
            });
            times = [...new Set(times)].sort();
            this.intermediateTimes = times.filter(time => 
                time !== this.trainingStart && time !== this.trainingEnd
            );
        },
    },
    async mounted() {
        await this.init();
    },
    beforeUnmount() {
        if (this.timeChecker) {
            clearInterval(this.timeChecker);
        }
    }
};
</script>

<style scoped>
form {
    margin-top: 20px;
}

form div {
    margin-bottom: 10px;
}

button[type="button"] {
    margin-left: 10px;
}

h3 {
    display: block;
}

form {
    margin-top: 20px;
}

form div {
    margin-bottom: 10px;
}

button[type="button"] {
    margin-left: 10px;
}

h3 {
    display: block;
}

.columns {
    display: flex;
    justify-content: space-between;
    width: calc(100% - 1em);
    overflow: hidden;
    height: 100%;
}

.column:first-child {
    flex: 1;
    overflow: hidden;
    height: 100%;justify-self: start;
    display: flex;
    flex-direction: column;
}

.column:last-child {
    overflow: auto;
}

textarea {
    width: 100%;
    margin-bottom: 10px;
}

ul {
    list-style-type: none;
    padding: 0;
}

.modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    z-index: 1000;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 50%;
    height: 50%;
    overflow: auto;
    background-color: rgba(200, 200, 200, 0.5);
}

.modal-content {
    background-color: #fefefe;
    padding: 20px;
    border: 1px solid #555;
    width: 100%;
    height: 100%;
    position: relative;
    box-shadow: 4px 3px 2px #999;
}

.close {
    position: absolute;
    top: 10px;
    right: 15px;
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    padding: 0;
    margin-bottom: 5px;
}

.multiselect {
    margin-bottom: 10px;
    width: 100%;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    padding: 8px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

input[type="text"] {
    width: 100%;
    padding: 5px;
    box-sizing: border-box;
}

input[type="time"] {
    width: 7em;
}

input[type="number"] {
    width: 5em;
    padding: 5px;
    box-sizing: border-box;
}

.dropdown {
    border: 1px solid #ccc;
    max-height: 200px;
    overflow-y: auto;
    position: absolute;
    background-color: white;
    z-index: 1000;
    width: calc(100% - 20px);
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
    max-width: 30em;
}

.dropdown div {
    padding: 8px;
    cursor: pointer;
}

.dropdown div:hover {
    background-color: #f0f0f0;
}

.clickable {
    cursor: pointer;
    color: #45a049;
}

.highlighted {
    background-color: #45a049;
    color: white;
    padding: 0.2em;
    border-radius: 4px;
}

.add-plan-item {
    border: 1px solid black;
    cursor: pointer;
    display: inline-block;
    width: 1.2em;
    height: 1.2em;
    text-align: center;
    line-height: 1.2em;
    font-weight: bold;
    margin-left: 5px;
    border-radius: 2px;
}

.cancel {
    border: 1px solid black;
    cursor: pointer;
    display: inline-block;
    width: 1.2em;
    height: 1.2em;
    text-align: center;
    line-height: 1.2em;
    font-weight: bold;
    margin-left: 5px;
    color: #ff0000;
    font-weight: bold;
    border-radius: 2px;
}

.add-plan-item:hover {
    background-color: #45a049;
    color: white;
}

.drag-handle {
    cursor: pointer;
}

.modal-body {
    display: flex;
    justify-content: space-between;
}

.modal-left {
    flex: 0 0 250px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-right: 20px;
}

.modal-right {
    flex: 1;
}

.img-icon {
    cursor: pointer;
}

img {
    max-width: 75%;
    max-height: 75%;
    position: absolute;
    left: 12.5%;
    top: 12.5%;
    box-shadow: 3px 3px 2px;
    border: 3px double #aaa;
}

.memberImage {
    position: fixed;
    max-width: 500px;
    max-height: 500px;
    top: calc(50% - 250px);
    left: calc(50% - 250px);
    border: 2px solid #555;
    box-shadow: 4px 4px 3px #aaa;
    overflow: hidden;
    padding: 3px;
}

.memberImage>img {
    max-width: 100%;
    max-height: 100%;
}

.groups {
    display: flex;
    flex-direction: row;
}

.diary {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.tag-header {
    margin: 0
}

.tag-list {
    margin: 0 0 1em 1.5em;
}
</style>
