<template>
    <BaseDialog
        :model-value="modelValue"
        @update:model-value="$emit('update:modelValue', $event)"
        :title="playerName"
        :is-modal="true"
        size="medium"
        @close="handleClose"
    >
        <div v-if="!loading && playerData" class="player-details-content">
            <table class="player-details-table">
                <tbody>
                    <tr>
                        <td class="label-cell">{{ $t('members.firstName') }} / {{ $t('members.lastName') }}</td>
                        <td class="value-cell" v-if="playerData.name">
                            <button class="copy-button" @click="copyToClipboard(playerData.name)" title="Kopieren">📋</button>
                            {{ playerData.name }}
                        </td>
                        <td class="value-cell missing" v-else>{{ $t('tournaments.dataNotRecorded') }}</td>
                    </tr>
                    <tr>
                        <td class="label-cell">{{ $t('members.birthdate') }}</td>
                        <td class="value-cell" v-if="playerData.birthDate">
                            <button class="copy-button" @click="copyToClipboard(formatDate(playerData.birthDate))" title="Kopieren">📋</button>
                            {{ formatDate(playerData.birthDate) }}
                        </td>
                        <td class="value-cell missing" v-else>{{ $t('tournaments.dataNotRecorded') }}</td>
                    </tr>
                    <tr>
                        <td class="label-cell">{{ $t('members.gender') }}</td>
                        <td class="value-cell" v-if="playerData.gender && playerData.gender !== 'unknown'">
                            <button class="copy-button" @click="copyToClipboard(formatGender(playerData.gender))" title="Kopieren">📋</button>
                            {{ formatGender(playerData.gender) }}
                        </td>
                        <td class="value-cell missing" v-else>{{ $t('tournaments.dataNotRecorded') }}</td>
                    </tr>
                    <tr>
                        <td class="label-cell">{{ $t('tournaments.address') }}</td>
                        <td class="value-cell" v-if="playerData.address">
                            <button class="copy-button" @click="copyToClipboard(playerData.address)" title="Kopieren">📋</button>
                            {{ playerData.address }}
                        </td>
                        <td class="value-cell missing" v-else>{{ $t('tournaments.dataNotRecorded') }}</td>
                    </tr>
                    <tr>
                        <td class="label-cell">{{ $t('members.emailAddress') }}</td>
                        <td class="value-cell" v-if="playerData.email">
                            <button class="copy-button" @click="copyToClipboard(playerData.email)" title="Kopieren">📋</button>
                            {{ playerData.email }}
                        </td>
                        <td class="value-cell missing" v-else>{{ $t('tournaments.dataNotRecorded') }}</td>
                    </tr>
                    <tr>
                        <td class="label-cell">{{ $t('members.phoneNumber') }}</td>
                        <td class="value-cell" v-if="playerData.phone">
                            <button class="copy-button" @click="copyToClipboard(playerData.phone)" title="Kopieren">📋</button>
                            {{ playerData.phone }}
                        </td>
                        <td class="value-cell missing" v-else>{{ $t('tournaments.dataNotRecorded') }}</td>
                    </tr>
                </tbody>
            </table>
            <div v-if="!hasAnyData" class="no-data">
                {{ $t('tournaments.noPlayerDataAvailable') }}
            </div>
        </div>
        <div v-else-if="loading" class="loading">
            {{ $t('messages.loading') }}...
        </div>
        <div v-else class="loading">
            {{ $t('tournaments.noPlayerDataAvailable') }}
        </div>
    </BaseDialog>
</template>

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

export default {
    name: 'PlayerDetailsDialog',
    components: {
        BaseDialog
    },
    props: {
        modelValue: {
            type: Boolean,
            default: false
        },
        playerId: {
            type: Number,
            default: null
        },
        isExternal: {
            type: Boolean,
            default: false
        },
        tournamentId: {
            type: [Number, String],
            required: true
        },
        clubId: {
            type: [Number, String],
            required: true
        },
        playerName: {
            type: String,
            default: ''
        }
    },
    emits: ['update:modelValue'],
    data() {
        return {
            playerData: null,
            loading: false
        };
    },
    computed: {
        hasAnyData() {
            if (!this.playerData) return false;
            return !!(this.playerData.name || this.playerData.birthDate || this.playerData.address || 
                     this.playerData.gender || this.playerData.email || this.playerData.phone);
        }
    },
    watch: {
        modelValue(newVal) {
            console.log('[PlayerDetailsDialog] modelValue changed:', newVal, 'playerId:', this.playerId);
            if (newVal && this.playerId) {
                // Lade Daten erst, wenn der Dialog geöffnet wird
                this.loadPlayerData();
            } else {
                this.playerData = null;
            }
        },
        playerId(newVal) {
            console.log('[PlayerDetailsDialog] playerId changed:', newVal, 'modelValue:', this.modelValue);
            // Wenn der Dialog bereits geöffnet ist und die playerId sich ändert, lade neue Daten
            if (this.modelValue && newVal) {
                this.loadPlayerData();
            }
        }
    },
    methods: {
        async loadPlayerData() {
            console.log('[PlayerDetailsDialog] loadPlayerData called, playerId:', this.playerId, 'isExternal:', this.isExternal, 'clubId:', this.clubId);
            if (!this.playerId) {
                console.warn('[PlayerDetailsDialog] Keine playerId');
                return;
            }
            if (!this.clubId || isNaN(Number(this.clubId))) {
                console.error('[PlayerDetailsDialog] Invalid clubId:', this.clubId);
                this.playerData = {
                    name: this.playerName,
                    error: true
                };
                this.loading = false;
                return;
            }
            
            this.loading = true;
            this.playerData = null;
            
            try {
                if (this.isExternal) {
                    // Lade externe Teilnehmer-Daten
                    // Lade alle externen Teilnehmer für dieses Turnier (ohne classId Filter = alle Klassen)
                    const response = await apiClient.post('/tournament/external-participants', {
                        clubId: Number(this.clubId),
                        tournamentId: this.tournamentId,
                        classId: null // null = alle externen Teilnehmer des Turniers
                    });
                    
                    const externalParticipant = Array.isArray(response.data) 
                        ? response.data.find(p => p.id === this.playerId)
                        : null;
                    
                    if (externalParticipant) {
                        this.playerData = {
                            name: `${externalParticipant.firstName || ''} ${externalParticipant.lastName || ''}`.trim(),
                            birthDate: externalParticipant.birthDate || null,
                            address: externalParticipant.address || null,
                            gender: externalParticipant.gender || null,
                            email: externalParticipant.email || null,
                            phone: null // Externe Teilnehmer haben keine Telefonnummer
                        };
                    } else {
                        this.playerData = {
                            name: this.playerName,
                            error: true
                        };
                    }
                } else {
                    // Lade interne Member-Daten
                    const response = await apiClient.get(`/clubmembers/get/${Number(this.clubId)}/true`);
                    const member = response.data.find(m => m.id === this.playerId);
                    
                    if (member) {
                        // Formatiere Adresse
                        let address = '';
                        const parts = [];
                        if (member.street) parts.push(member.street);
                        if (member.postalCode) parts.push(member.postalCode);
                        if (member.city) parts.push(member.city);
                        address = parts.join(', ');
                        
                        // Formatiere Telefonnummer
                        let phone = '';
                        if (member.contacts && Array.isArray(member.contacts)) {
                            const phoneContacts = member.contacts
                                .filter(c => c.type === 'phone')
                                .map(c => c.value);
                            phone = phoneContacts.join(', ');
                        } else if (member.phone) {
                            phone = member.phone;
                        }
                        
                        // Formatiere E-Mail
                        let email = '';
                        if (member.contacts && Array.isArray(member.contacts)) {
                            const emailContacts = member.contacts
                                .filter(c => c.type === 'email')
                                .map(c => c.value);
                            email = emailContacts.join(', ');
                        } else if (member.email) {
                            email = member.email;
                        }
                        
                        this.playerData = {
                            name: `${member.firstName || ''} ${member.lastName || ''}`.trim(),
                            birthDate: member.birthDate || null,
                            address: address || null,
                            gender: member.gender || null,
                            email: email || null,
                            phone: phone || null
                        };
                    }
                }
            } catch (error) {
                console.error('Fehler beim Laden der Spielerdaten:', error);
                this.playerData = {
                    name: this.playerName,
                    error: true
                };
            } finally {
                this.loading = false;
            }
        },
        formatDate(dateString) {
            if (!dateString) return '';
            try {
                const date = new Date(dateString);
                if (isNaN(date.getTime())) {
                    // Versuche, verschiedene Datumsformate zu parsen
                    const ddmmyyyy = dateString.match(/(\d{1,2})\.(\d{1,2})\.(\d{4})/);
                    if (ddmmyyyy) {
                        return dateString; // Bereits im richtigen Format
                    }
                    return dateString;
                }
                const day = String(date.getDate()).padStart(2, '0');
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const year = date.getFullYear();
                return `${day}.${month}.${year}`;
            } catch (e) {
                return dateString;
            }
        },
        formatGender(gender) {
            if (!gender || gender === 'unknown') return '';
            const genderMap = {
                'male': this.$t('members.genderMale'),
                'female': this.$t('members.genderFemale'),
                'diverse': this.$t('members.genderDiverse')
            };
            return genderMap[gender] || gender;
        },
        handleClose() {
            this.$emit('update:modelValue', false);
        },
        async copyToClipboard(text) {
            try {
                await navigator.clipboard.writeText(text);
                // Optional: Feedback anzeigen (z.B. kurz "Kopiert!" anzeigen)
            } catch (err) {
                console.error('Fehler beim Kopieren:', err);
                // Fallback für ältere Browser
                const textArea = document.createElement('textarea');
                textArea.value = text;
                textArea.style.position = 'fixed';
                textArea.style.opacity = '0';
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                } catch (fallbackErr) {
                    console.error('Fallback-Kopieren fehlgeschlagen:', fallbackErr);
                }
                document.body.removeChild(textArea);
            }
        }
    }
};
</script>

<style scoped>
.player-details-content {
    padding: 1rem;
}

.player-details-table {
    width: 100%;
    border-collapse: collapse;
}

.player-details-table tbody tr {
    border-bottom: 1px solid #e0e0e0;
}

.player-details-table tbody tr:last-child {
    border-bottom: none;
}

.player-details-table .label-cell {
    padding: 0.75rem 1rem 0.75rem 0;
    font-weight: 600;
    color: #333;
    vertical-align: top;
    width: 40%;
    min-width: 150px;
}

.player-details-table .value-cell {
    padding: 0.75rem 0;
    color: #666;
    vertical-align: top;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.copy-button {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 1.1em;
    padding: 0.25rem 0.5rem;
    opacity: 0.6;
    transition: opacity 0.2s;
    flex-shrink: 0;
}

.copy-button:hover {
    opacity: 1;
}

.copy-button:active {
    opacity: 0.8;
}

.value-cell.missing {
    color: #c62828;
    font-style: italic;
    opacity: 0.85;
}

.no-data {
    text-align: center;
    padding: 2rem;
    color: #999;
    font-style: italic;
}

.loading {
    text-align: center;
    padding: 2rem;
    color: #666;
}
</style>
