<template>
    <BaseDialog
        :model-value="modelValue"
        @update:model-value="$emit('update:modelValue', $event)"
        :title="date && date !== 'new' ? $t('memberGallery.titleWithDate') : $t('memberGallery.title')"
        size="large"
        :close-on-overlay="true"
        @close="handleClose"
    >
        <div class="gallery-dialog-content">
            <div class="gallery-controls">
                <label for="gallery-size">{{ $t('memberGallery.imageSize') }}:</label>
                <select id="gallery-size" v-model="gallerySize" @change="loadGalleryMembers" :disabled="galleryLoading">
                    <option :value="100">100x100 px</option>
                    <option :value="150">150x150 px</option>
                    <option :value="200">200x200 px</option>
                </select>
            </div>
            <div v-if="galleryLoading" class="gallery-loading">{{ $t('memberGallery.loading') }}</div>
            <div v-else-if="visibleGalleryMembers.length > 0" class="gallery-members-grid" :style="{ gridTemplateColumns: 'repeat(auto-fill, ' + gallerySize + 'px)' }">
                <div 
                    v-for="member in visibleGalleryMembers" 
                    :key="member.memberId"
                    class="gallery-member-item"
                    :class="{ 'is-participant': date && date !== 'new' && isParticipant(member.memberId) }"
                    :style="{ width: gallerySize + 'px', minWidth: gallerySize + 'px', height: gallerySize + 'px' }"
                    @click="handleGalleryMemberClick(member)"
                >
                    <img 
                        v-if="member.imageUrl"
                        :src="member.imageUrl" 
                        :alt="member.fullName"
                        class="gallery-member-image"
                        @error="handleImageError(member)"
                        @load="handleImageLoad(member)"
                    />
                    <div v-else class="gallery-member-placeholder">{{ $t('memberGallery.noImage') }}</div>
                    <div class="gallery-member-name">{{ member.fullName }}</div>
                </div>
            </div>
            <div v-else class="gallery-error">
                {{ galleryError || $t('memberGallery.noMembersWithImages') }}
            </div>
        </div>
    </BaseDialog>
</template>

<script>
import BaseDialog from './BaseDialog.vue';
import apiClient from '../apiClient.js';

export default {
    name: 'MemberGalleryDialog',
    components: {
        BaseDialog
    },
    props: {
        modelValue: {
            type: Boolean,
            default: false
        },
        currentClub: {
            type: Number,
            required: true
        },
        date: {
            type: [Object, String],
            default: null
        },
        isParticipant: {
            type: Function,
            default: () => false
        },
        shouldShowMember: {
            type: Function,
            default: () => true
        },
        participantStatusMap: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['update:modelValue', 'member-click'],
    data() {
        return {
            galleryLoading: false,
            galleryImageUrl: null,
            galleryError: '',
            gallerySize: 200,
            galleryMembers: [],
            isInitialLoad: true
        };
    },
    watch: {
        modelValue(newVal) {
            if (newVal) {
                this.isInitialLoad = true;
                this.loadGalleryMembers();
            } else {
                this.handleClose();
            }
        }
    },
    computed: {
        visibleGalleryMembers() {
            return (this.galleryMembers || []).filter((member) => {
                const status = this.participantStatusMap?.[member.memberId] || '';
                if (status === 'excused') {
                    return false;
                }
                return this.shouldShowMember(member);
            });
        }
    },
    methods: {
        updateGallerySizeBasedOnCount() {
            const count = this.galleryMembers.length;
            if (count < 11) {
                this.gallerySize = 200;
            } else if (count < 22) {
                this.gallerySize = 150;
            } else {
                this.gallerySize = 100;
            }
        },
        async loadGalleryMembers() {
            if (!this.currentClub || this.galleryLoading) {
                return;
            }
            this.galleryLoading = true;
            this.galleryError = '';
            this.galleryImageUrl = null;
            this.revokeGalleryImage();
            try {
                const response = await apiClient.get(`/clubmembers/gallery/${this.currentClub}?format=json&size=${this.gallerySize}`);
                const members = (response.data.members || []).filter(member => this.shouldShowMember(member));
                
                // Setze Größe basierend auf Anzahl der Mitglieder nur beim ersten Laden
                if (this.isInitialLoad) {
                    this.galleryMembers = members; // Temporär setzen für count
                    this.updateGallerySizeBasedOnCount();
                    this.isInitialLoad = false;
                }
                
                // Lade Bilder als Blobs und erstelle ObjectURLs
                this.galleryMembers = await Promise.all(members.map(async (member) => {
                    try {
                        const imageUrl = await this.loadMemberImageAsBlob(member.memberId);
                        console.log(`[loadGalleryMembers] Member ${member.memberId} (${member.fullName}): imageUrl =`, imageUrl ? 'OK' : 'null');
                        return {
                            ...member,
                            imageUrl: imageUrl || null
                        };
                    } catch (error) {
                        console.error(`[loadGalleryMembers] Fehler beim Laden des Bildes für Mitglied ${member.memberId}:`, error);
                        return {
                            ...member,
                            imageUrl: null
                        };
                    }
                }));
                
                // Sortiere nach Vorname, dann Nachname
                this.galleryMembers.sort((a, b) => {
                    const firstNameA = (a.firstName || '').toLowerCase();
                    const firstNameB = (b.firstName || '').toLowerCase();
                    const lastNameA = (a.lastName || '').toLowerCase();
                    const lastNameB = (b.lastName || '').toLowerCase();
                    
                    if (firstNameA !== firstNameB) {
                        return firstNameA.localeCompare(firstNameB);
                    }
                    return lastNameA.localeCompare(lastNameB);
                });
                
                console.log('[loadGalleryMembers] Geladene Mitglieder:', this.galleryMembers.map(m => ({ id: m.memberId, name: m.fullName, hasImage: !!m.imageUrl })));
            } catch (error) {
                console.error('Fehler beim Laden der Galerie:', error);
                this.galleryError = error?.response?.data?.error || 'Galerie konnte nicht geladen werden.';
                this.galleryMembers = [];
            } finally {
                this.galleryLoading = false;
            }
        },
        async loadMemberImageAsBlob(memberId) {
            try {
                const response = await apiClient.get(`/clubmembers/image/${this.currentClub}/${memberId}`, { responseType: 'blob' });
                if (!response.data || response.data.size === 0) {
                    console.warn(`[loadMemberImageAsBlob] Leeres Blob für Mitglied ${memberId}`);
                    return null;
                }
                const objectUrl = URL.createObjectURL(response.data);
                console.log(`[loadMemberImageAsBlob] ObjectURL erstellt für Mitglied ${memberId}:`, objectUrl.substring(0, 50) + '...');
                return objectUrl;
            } catch (error) {
                // 404 ist OK - Mitglied hat kein Bild
                if (error?.response?.status === 404) {
                    console.log(`[loadMemberImageAsBlob] Kein Bild für Mitglied ${memberId} (404)`);
                    return null;
                }
                console.error(`[loadMemberImageAsBlob] Fehler beim Laden des Bildes für Mitglied ${memberId}:`, error);
                return null;
            }
        },
        revokeGalleryImage() {
            if (this.galleryImageUrl) {
                URL.revokeObjectURL(this.galleryImageUrl);
                this.galleryImageUrl = null;
            }
        },
        handleClose() {
            this.revokeGalleryImage();
            // Revoke all object URLs
            this.galleryMembers.forEach(member => {
                if (member.imageUrl) {
                    URL.revokeObjectURL(member.imageUrl);
                }
            });
            this.galleryMembers = [];
            this.isInitialLoad = true;
            this.$emit('update:modelValue', false);
        },
        handleGalleryMemberClick(member) {
            this.$emit('member-click', member);
        },
        handleImageError(member) {
            console.error(`[handleImageError] Bild konnte nicht geladen werden für Mitglied ${member.memberId} (${member.fullName}), URL:`, member.imageUrl);
            // Setze imageUrl auf null, damit der Placeholder angezeigt wird
            member.imageUrl = null;
        },
        handleImageLoad(member) {
            console.log(`[handleImageLoad] Bild erfolgreich geladen für Mitglied ${member.memberId} (${member.fullName})`);
        }
    },
    beforeUnmount() {
        this.handleClose();
    }
};
</script>

<style scoped>
.gallery-dialog-content {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    padding: 0;
    min-height: 60vh;
    max-height: 70vh;
    overflow: auto;
}

.gallery-controls {
    width: 100%;
    padding: 12px 16px;
    border-bottom: 1px solid var(--border-color, #ddd);
    display: flex;
    align-items: center;
    gap: 12px;
    background: var(--surface-muted);
    flex-shrink: 0;
    position: relative;
    z-index: 10;
}

.gallery-controls label {
    font-weight: 500;
    color: var(--text-color, #333);
}

.gallery-controls select {
    padding: 0.6rem 0.8rem;
    border: 1px solid var(--border-color, #ddd);
    border-radius: 10px;
    font-size: 14px;
    background: var(--surface-color);
    color: var(--text-color, #333);
    cursor: pointer;
}

.gallery-controls select:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.gallery-loading,
.gallery-error {
    font-size: 1rem;
    color: var(--text-color, #333);
}

.gallery-members-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, max-content);
    gap: 0;
    padding: 0;
    width: 100%;
    position: relative;
    z-index: 1;
    align-items: start;
    box-sizing: border-box;
    justify-items: start;
}

.gallery-member-item {
    display: block;
    cursor: pointer;
    padding: 0;
    border: none;
    border-radius: 0;
    transition: all 0.2s ease;
    margin: 0;
    box-sizing: border-box;
    overflow: hidden;
    position: relative;
}

.gallery-member-item:hover {
    background-color: transparent;
}

.gallery-member-item.is-participant {
    box-shadow:
        inset 0 0 0 4px #22c55e;
}

.gallery-member-item.is-participant::after {
    content: '✓';
    position: absolute;
    top: 8px;
    right: 8px;
    width: 26px;
    height: 26px;
    border-radius: 999px;
    background: #16a34a;
    color: #ffffff;
    font-size: 16px;
    font-weight: 800;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 12;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
    pointer-events: none;
}

.gallery-member-image {
    object-fit: cover;
    border-radius: 0;
    margin: 0;
    pointer-events: none; /* Prevent image from blocking clicks on parent */
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    max-width: 100%;
    max-height: 100%;
    border: none !important;
}

.gallery-member-name {
    font-size: 12px;
    text-align: center;
    color: #fff7e8;
    font-weight: 600;
    margin: 0;
    padding: 4px 8px;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.5) !important;
    z-index: 10;
}

.gallery-member-item.is-participant .gallery-member-name {
    color: #ffffff;
    background-color: rgba(22, 163, 74, 0.82) !important;
    font-weight: 700;
}

.gallery-member-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--surface-muted);
    border-radius: 0;
    color: var(--text-muted);
    font-size: 12px;
    margin: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
</style>
