<template>
    <div>
        <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">{{ 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" id="trainingStart" v-model="trainingStart" />
                </div>
                <div>
                    <label for="trainingEnd">Trainingsende:</label>
                    <input type="time" 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</h3>
            <form @submit.prevent="updateTrainingTimes">
                <div>
                    <label for="editTrainingStart">Trainingsbeginn:</label>
                    <input type="time" id="editTrainingStart" v-model="trainingStart" />
                </div>
                <div>
                    <label for="editTrainingEnd">Trainingsende:</label>
                    <input type="time" id="editTrainingEnd" v-model="trainingEnd" />
                </div>
                <button type="submit">Zeiten aktualisieren</button>
            </form>
        </div>

        <!-- Teilnehmer und Aktivitäten -->
        <div v-if="date !== 'new' && date !== null">
            <div class="columns">
                <div class="column">
                    <h3>Teilnehmer</h3>
                    <ul>
                        <li v-for="member in members" :key="member.id">
                            <label>
                                <input type="checkbox" :value="member.id" @change="toggleParticipant(member.id)"
                                    :checked="isParticipant(member.id)">
                                {{ member.firstName }} {{ member.lastName }}
                            </label>
                        </li>
                    </ul>
                </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>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';

export default {
    name: 'DiaryView',
    data() {
        return {
            date: null,
            dates: [],
            showForm: false,
            newDate: '',
            trainingStart: '',
            trainingEnd: '',
            members: [],
            participants: [],
            newActivity: '',
            activities: [],
        };
    },
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub']),
    },
    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 }));
            }
        },
        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;

                await this.loadMembers();
                await this.loadParticipants(dateId);
                await this.loadActivities(dateId); 
            } else {
                this.newDate = '';
                this.trainingStart = '';
                this.trainingEnd = '';
                this.participants = [];
            }
        },
        setCurrentDate() {
            const today = new Date().toISOString().split('T')[0];
            this.newDate = today;
        },
        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 = '';
                this.trainingEnd = '';
                console.log(this.date);
            } catch (error) {
                console.error('Fehler beim Erstellen des Datums:', error);
                alert('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
            }
        },
        async updateTrainingTimes() {
            try {
                const dateId = this.date.id; 
                const response = 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/${this.currentClub}`);
            this.members = response.data;
        },
        async loadParticipants(dateId) {
            const response = await apiClient.get(`/participants/${dateId}`);
            this.participants = response.data.map(participant => participant.memberId);
        },
        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 loadActivities(dateId) {
            const response = await apiClient.get(`/activities/${dateId}`);
            this.activities = response.data;
        },
        async addActivity() {
            const dateId = this.date.id; 
            if (this.newActivity) {
                const response = await apiClient.post('/activities/add', {
                    diaryDateId: dateId,
                    description: this.newActivity
                });
                this.activities.push(response.data);
                this.newActivity = '';
            }
        }
    },
    async mounted() {
        await this.init();
    }
};
</script>

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

form div {
    margin-bottom: 10px;
}

button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
}

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

button:hover {
    background-color: #45a049;
}

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

.column {
    flex: 0 0 45%;
}

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

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

</style>
