<template>
    <div>
        <h2>Mitglieder</h2>
        <div>
            <button @click="createPhoneList">Telefonliste generieren</button>Es werden nur aktive Mitglieder ausgegeben
        </div>
        <div class="newmember">
            <div class="toggle-new-member">
                <span @click="toggleNewMember">
                    <span class="add">{{ memberFormIsOpen ? '-' : '+' }}</span>
                    {{ memberToEdit === null ? "Neues Mitglied" : "Mitglied bearbeiten" }}
                </span>
                <button v-if="memberToEdit !== null" @click="resetToNewMember">Neues Mitglied anlegen</button>
            </div>
            <div v-if="memberFormIsOpen" class="new-member-form">
                <label><span>Vorname:</span> <input type="text" v-model="newFirstname"></label>
                <label><span>Nachname:</span> <input type="text" v-model="newLastname"></label>
                <label><span>Straße:</span> <input type="text" v-model="newStreet"></label>
                <label><span>Ort:</span> <input type="text" v-model="newCity"></label>
                <label><span>Geburtsdatum:</span> <input type="date" v-model="newBirthdate"></label>
                <label><span>Telefon-Nr.:</span> <input type="text" v-model="newPhone"></label>
                <label><span>Email-Adresse:</span> <input type="email" v-model="newEmail"></label>
                <label><span>Aktiv:</span> <input type="checkbox" v-model="newActive"></label>
                <label><span>Pics in Internet erlaubt:</span> <input type="checkbox" v-model="newPicsInInternetAllowed"></label>
                <label><span>Testmitgliedschaft:</span> <input type="checkbox" v-model="testMembership" </label>
                    <label><span>Bild:</span> <input type="file" @change="onFileSelected"></label>
                    <div v-if="memberImagePreview">
                        <img :src="memberImagePreview" alt="Vorschau des Mitgliedsbildes"
                            style="max-width: 200px; max-height: 200px;">
                    </div>
                    <div>
                        <button @click="addNewMember">{{ memberToEdit ? 'Ändern' : 'Anlegen' }}</button>
                        <button @click="resetNewMember" v-if="memberToEdit === null" class="cancel-action">Felder
                            leeren</button>
                    </div>
            </div>
        </div>
        <div>
            <input type="checkbox" v-model="showInactiveMembers"> Inaktive Mitglieder anzeigen
        </div>
        <div>
            <table>
                <thead>
                    <tr>
                        <th>Bild (Inet?)</th>
                        <th>Testm.</th>
                        <th>Name, Vorname</th>
                        <th>Adresse</th>
                        <th>Geburtsdatum</th>
                        <th>Telefon-Nr.</th>
                        <th>Email-Adresse</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <template v-for="member in members" :key="member.id">
                        <tr v-if="member.active || showInactiveMembers" class="member-row" @click="editMember(member)">
                            <td>
                                <img v-if="member.imageUrl" :src="member.imageUrl" alt="Mitgliedsbild"
                                    style="max-width: 50px; max-height: 50px;"
                                    @click.stop="openImageModal(member.imageUrl)">
                                <span>{{ member.picsInInternetAllowed ? '✓' : '' }}</span>
                            </td>
                            <td>{{ member.testMembership ? '*' : '' }}</td>
                            <td>{{ member.lastName }}, {{ member.firstName }}</td>
                            <td>{{ member.street }}, {{ member.city }}</td>
                            <td>{{ getFormattedBirthdate(member.birthDate) }}</td>
                            <td>{{ member.phone }}</td>
                            <td>{{ member.email }}</td>
                            <td>
                                <button @click.stop="openNotesModal(member)">Notizen</button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>

        <div v-if="showImageModal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeImageModal">&times;</span>
                <img :src="selectedImageUrl" alt="Großes Mitgliedsbild" style="max-width: 100%; max-height: 100%;">
            </div>
        </div>

        <div v-if="showNotesModal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeNotesModal">&times;</span>
                <h3>Notizen für {{ memberToEdit.firstName }} {{ memberToEdit.lastName }}</h3>
                <div>
                    <textarea v-model="newNoteContent" placeholder="Neue Notiz" rows="4" cols="30"></textarea>
                    <button @click="addNote">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>
</template>

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

export default {
    name: 'MembersView',
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub']),
    },
    data() {
        return {
            members: [],
            memberFormIsOpen: false,
            newFirstname: '',
            newLastname: '',
            newStreet: '',
            newCity: '',
            newBirthdate: '01.01.2010',
            newPhone: '',
            newEmail: '',
            newActive: true,
            memberToEdit: null,
            memberImage: null, 
            memberImagePreview: null,
            notes: [],
            newNoteContent: '',
            showNotesModal: false,
            showImageModal: false, 
            selectedImageUrl: null,
            testMembership: false,
            showInactiveMembers: false,
            newPicsInInternetAllowed: false
        }
    },
    async mounted() {
        await this.init();
    },
    methods: {
        async init() {
            await this.loadMembers();
        },
        async loadMembers() {
            const response = await apiClient.get(`/clubmembers/get/${this.currentClub}/true`);
            this.members = response.data.sort((a, b) => {
                const lastNameA = a.lastName ? a.lastName.toLowerCase() : '';
                const lastNameB = b.lastName ? b.lastName.toLowerCase() : '';
                if (lastNameA && !lastNameB) return -1;
                if (!lastNameA && lastNameB) return 1; 
                if (lastNameA && lastNameB) {
                    const lastNameCompare = lastNameA.localeCompare(lastNameB, 'de-DE');
                    if (lastNameCompare !== 0) return lastNameCompare;
                }
                const firstNameA = a.firstName ? a.firstName.toLowerCase() : '';
                const firstNameB = b.firstName ? b.firstName.toLowerCase() : '';
                return firstNameA.localeCompare(firstNameB, 'de-DE');
            });
            this.members.forEach(member => {
                this.loadMemberImage(member);
            });
        },
        toggleNewMember() {
            this.memberFormIsOpen = !this.memberFormIsOpen;
        },
        resetNewMember() {
            this.newFirstname = '';
            this.newLastname = '';
            this.newStreet = '';
            this.newCity = '';
            this.newBirthdate = '01.01.2010';
            this.newPhone = '';
            this.newEmail = '';
            this.newActive = true;
            this.newPicsInInternetAllowed = false;
            this.testMembership = true;
            this.memberImage = null;
            this.memberImagePreview = null;
        },
        onFileSelected(event) {
            const file = event.target.files[0];
            this.memberImage = file;
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.memberImagePreview = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        },
        async addNewMember() {
            const memberData = {
                firstname: this.newFirstname,
                lastname: this.newLastname,
                street: this.newStreet,
                city: this.newCity,
                birthdate: this.newBirthdate,
                phone: this.newPhone,
                email: this.newEmail,
                active: this.newActive,
                id: this.memberToEdit ? this.memberToEdit.id : null,
                testMembership: this.testMembership,
                picsInInternetAllowed: this.newPicsInInternetAllowed,
            };

            let response;
            try {
                response = await apiClient.post(`/clubmembers/set/${this.currentClub}`, memberData);
                this.loadMembers();
            } catch (error) {
                console.error("Fehler beim Speichern des Mitglieds:", error);
                return;
            }

            if (this.memberImage) {
                const formData = new FormData();
                formData.append('image', this.memberImage);
                formData.append('clubId', this.currentClub);  
                try {
                    await apiClient.post(`/clubmembers/image/${this.currentClub}/${this.memberToEdit.id}`, formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });
                } catch (error) {
                    console.error("Fehler beim Hochladen des Bildes:", error);
                }
            }

            this.resetNewMember();
            this.memberFormIsOpen = false;
        },
        async editMember(member) {
            console.log(member.birthDate);
            this.memberToEdit = member;
            this.memberFormIsOpen = true;
            this.newFirstname = member.firstName;
            this.newLastname = member.lastName;
            this.newStreet = member.street;
            this.newCity = member.city;
            this.newPhone = member.phone;
            this.newEmail = member.email;
            this.newActive = member.active;
            const date = new Date(member.birthDate);
            this.newBirthdate = date.toISOString().split('T')[0];
            this.testMembership = member.testMembership;
            this.newPicsInInternetAllowed = member.picsInInternetAllowed;
            try {
                const response = await apiClient.get(`/clubmembers/image/${member.id}`, { 
                    responseType: 'blob'
                });
                this.memberImagePreview = URL.createObjectURL(response.data);
            } catch (error) {
                console.error("Fehler beim Laden des Bildes:", error);
                this.memberImagePreview = null;
            }
        },
        resetToNewMember() {
            this.memberToEdit = null;
            this.resetNewMember();
        },
        async loadNotes(member) {
            this.selectedMember = member;
            const response = await apiClient.get(`/membernotes/${member.id}`, {
                params: { clubId: this.currentClub }
            });
            this.notes = response.data;
            this.showNotesModal = true;
        },
        async addNote() {
            const response = await apiClient.post('/membernotes', {
                memberId: this.selectedMember.id,
                content: this.newNoteContent,
                clubId: this.currentClub
            });
            this.notes = response.data;
            this.newNoteContent = '';
        },
        async deleteNote(noteId) {
            await apiClient.delete(`/membernotes/${noteId}`, {
                data: { clubId: this.currentClub }
            });
            this.notes = response.data;
        },
        openNotesModal(member) {
            this.memberToEdit = member;
            this.showNotesModal = true;
        },
        closeNotesModal() {
            this.showNotesModal = false;
        },
        openImageModal(imageUrl) {
            this.selectedImageUrl = imageUrl;
            this.showImageModal = true;
        },
        closeImageModal() {
            this.showImageModal = false;
            this.selectedImageUrl = null;
        },
        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) {
                console.error("Failed to load member image:", error);
                member.imageUrl = null; 
            }
        },
        async createPhoneList() {
            const activeMembers = this.members.filter(member => member.active);
            const pdfGenerator = new PDFGenerator();
            pdfGenerator.addPhoneList(activeMembers);
            pdfGenerator.save('Telefonliste.pdf');
        },
        getFormattedBirthdate(birthDate) {
            const date = new Date(birthDate);
            return `${String(date.getDate()).padStart(2, '0')}.${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()}`;
        },
    }
}
</script>

<style scoped>
table {
    border-collapse: collapse;
}

thead>tr>th {
    border-bottom: 1px solid #000;
}

table th,
table td {
    padding-right: 2em;
}

table td {
    cursor: pointer;
}

.toggle-new-member {
    cursor: pointer;
    font-weight: bold;
}

.add {
    border: 1px solid #999;
    margin: 0 6px 4px 0;
    border-radius: 50%;
    height: 15px;
    width: 15px;
    display: inline-block;
    line-height: 15px;
    text-align: center;
    box-shadow: 2px 2px 2px #bbb;
}

.newmember {
    border: 1px solid #999;
    margin-bottom: 2em;
}

.new-member-form {
    display: flex;
    flex-direction: column;
}

.new-member-form>label>span {
    width: 10em;
    display: inline-block;
}

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

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

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

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
</style>
