<template>
    <div>
        <h2>{{ $t('club.title') }} {{ club.name }}</h2>
        <div v-if="accessAllowed">
            <div v-if="openRequests.length > 0">
                <h3>{{ $t('club.openAccessRequests') }}</h3>
                <!-- Hier könntest du die offenen Anfragen anzeigen -->
            </div>
            <div>
                <h3>{{ $t('club.members') }}</h3>
                <ul class="members">
                    <li v-for="member in displayedMembers" :key="member.id" class="member-item">
                        <span class="gender-symbol" :class="'gender-' + (member.gender || 'unknown')" :title="labelGender(member.gender)">{{ genderSymbol(member.gender) }}</span>
                        <span class="gender-name" :class="['gender-' + (member.gender || 'unknown'), { 'is-test': member.testMembership }]">
                            {{ member.lastName }}, {{ member.firstName }}
                        </span>
                    </li>
                </ul>
            </div>
            <div>
                <h3>{{ $t('club.diary') }}</h3>
            </div>
        </div>
        <div v-else>
            <div v-if="accessRequested" class="access-requested">
                {{ $t('club.accessRequestPending') }}
            </div>
            <div v-else>
                {{ $t('club.noAccess') }}
                <button @click="requestAccess" :disabled="accessRequested">{{ $t('club.requestAccess') }}</button>
            </div>
        </div>
    </div>

    
    <!-- Info Dialog -->
    <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
    />
    
    <!-- Confirm Dialog -->
    <ConfirmDialog
        v-model="confirmDialog.isOpen"
        :title="confirmDialog.title"
        :message="confirmDialog.message"
        :details="confirmDialog.details"
        :type="confirmDialog.type"
        @confirm="handleConfirmResult(true)"
        @cancel="handleConfirmResult(false)"
    />
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import apiClient from '../apiClient';
import { buildInfoConfig, buildConfirmConfig, safeErrorMessage } from '../utils/dialogUtils.js';

import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';
export default {
    name: "ClubView",
    data() {
        return {
            // Dialog States
            infoDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info'
            },
            confirmDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
                resolveCallback: null
            },
            club: {
                name: '',
            },
            openRequests: [],
            accessAllowed: false,
            accessRequested: false
        }
    },
    methods: {
        // Dialog Helper Methods
        async showInfo(title, message, details = '', type = 'info') {
            this.infoDialog = buildInfoConfig({ title, message, details, type });
        },
        
        async showConfirm(title, message, details = '', type = 'info', options = {}) {
            return new Promise((resolve) => {
                this.confirmDialog = buildConfirmConfig({
                    title,
                    message,
                    details,
                    type,
                    resolveCallback: resolve,
                    ...options,
                });
            });
        },
        
        handleConfirmResult(confirmed) {
            if (this.confirmDialog.resolveCallback) {
                this.confirmDialog.resolveCallback(confirmed);
                this.confirmDialog.resolveCallback = null;
            }
            this.confirmDialog.isOpen = false;
        },
        
        getClubId() {
            return this.currentClub || this.$route.params.clubId;
        },
        canAccessClub() {
            return this.isClubOwner || this.userRole === 'admin'
                || this.hasPermission('members', 'read')
                || this.hasPermission('diary', 'read')
                || this.hasPermission('statistics', 'read')
                || this.hasPermission('tournaments', 'read')
                || this.hasPermission('schedule', 'read');
        },
        async loadClub() {
            try {
                const clubId = this.getClubId();
                this.accessRequested = false;
                const response = await apiClient.get(`/clubs/${clubId}`);
                // apiClient behandelt 4xx als "erfolgreich" -> Status selbst prüfen
                if (response.status === 403 && response.data?.status) {
                    const club = this.clubs.find(c => String(c.id) === String(clubId));
                    this.club = club || { name: '' };
                    this.accessAllowed = false;
                    this.accessRequested = response.data.status === 'requested';
                    return;
                }
                if (response.status >= 400) {
                    throw new Error('club_access_error');
                }
                this.club = response.data || { name: '' };
                this.accessAllowed = true;
            } catch (error) {
                this.accessAllowed = false;
                const message = safeErrorMessage(error, this.$t('club.accessDenied'));
                await this.showInfo(this.$t('messages.error'), message, '', 'error');
            }
        },
        async loadOpenRequests() {
            try {
                if (!this.accessAllowed) return;
                const clubId = this.getClubId();
                const response = await apiClient.get(`/clubmembers/notapproved/${clubId}`);
                this.openRequests = response.data;
            } catch (error) {
                this.showInfo(this.$t('messages.error'), this.$t('club.errorLoadingRequests'), '', 'error');
            }
        }, 
        async requestAccess() {
            try {
                if (this.accessRequested) return;
                const clubId = this.getClubId();
                const response = await apiClient.get(`/clubs/request/${clubId}`);
                if (response.status === 200) {
                    this.accessRequested = true;
                    await this.showInfo(this.$t('messages.info'), this.$t('club.accessRequested'), '', 'info');
                }
            } catch (error) {
                if (error?.response?.status === 409) {
                    this.accessRequested = true;
                    await this.showInfo(this.$t('messages.info'), this.$t('club.accessRequested'), '', 'info');
                    return;
                }
                const message = safeErrorMessage(error, this.$t('club.accessRequestFailed'));
                await this.showInfo(this.$t('messages.error'), message, '', 'error');
            }
        },
        labelGender(g) {
            const v = (g || 'unknown');
            if (v === 'male') return this.$t('members.genderMale');
            if (v === 'female') return this.$t('members.genderFemale');
            if (v === 'diverse') return this.$t('members.genderDiverse');
            return this.$t('members.genderUnknown');
        },
        genderSymbol(g) {
            const v = (g || 'unknown');
            if (v === 'male') return '♂';
            if (v === 'female') return '♀';
            if (v === 'diverse') return '⚧';
            return '';
        }
    },
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub', 'clubs', 'hasPermission', 'isClubOwner', 'userRole']),
        displayedMembers() {
            const members = Array.isArray(this.club.members) ? this.club.members : [];
            const onlyActive = members.filter(m => m && (m.active === true));
            return onlyActive.sort((a, b) => {
                const lnA = (a.lastName || '').toLowerCase();
                const lnB = (b.lastName || '').toLowerCase();
                if (lnA && !lnB) return -1;
                if (!lnA && lnB) return 1;
                if (lnA && lnB) {
                    const cmp = lnA.localeCompare(lnB, 'de-DE');
                    if (cmp !== 0) return cmp;
                }
                const fnA = (a.firstName || '').toLowerCase();
                const fnB = (b.firstName || '').toLowerCase();
                return fnA.localeCompare(fnB, 'de-DE');
            });
        }
    },
    async mounted() {
        await this.loadClub();
        if (this.accessAllowed) {
            await this.loadOpenRequests();
        }
    }
}
</script>

<style lang="scss" scoped>
h2 {
    display: block;
}

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

.members { margin-top: .25rem; }
.member-item { padding: .15rem 0; }
.gender-symbol, .gender-name { background: transparent; border: none; }
.gender-name.gender-male { color: #1a73e8; }
.gender-name.gender-female { color: #d81b60; }
.gender-name.gender-diverse { color: #6a1b9a; }
.gender-name.gender-unknown { color: #444; }
.gender-symbol.gender-male { color: #1a73e8; }
.gender-symbol.gender-female { color: #d81b60; }
.gender-symbol.gender-diverse { color: #6a1b9a; }
.gender-symbol.gender-unknown { color: #444; }
.gender-symbol { margin-right: .35rem; opacity: .9; font-size: 1.05em; display: inline-block; width: 1.1em; text-align: center; }
.is-test { font-style: italic; }
.access-requested {
    margin: 0.5rem 0;
    color: #2e7d32;
    font-weight: 600;
}
</style>
