<template>
    <div class="training-groups-tab">
        <div class="groups-section">
            <div class="section-header">
                <h3>{{ $t('trainingGroupsTab.groups') }}</h3>
                <button @click="showAddGroupForm = true" class="btn-primary">{{ $t('trainingGroupsTab.newGroup') }}</button>
            </div>

            <!-- Add Group Form -->
            <div v-if="showAddGroupForm" class="add-group-form">
                <input 
                    v-model="newGroupName" 
                    type="text" 
                    :placeholder="$t('trainingGroupsTab.groupName')" 
                    @keyup.enter="createGroup"
                    class="input-field"
                />
                <button @click="createGroup" class="btn-primary">{{ $t('trainingGroupsTab.create') }}</button>
                <button @click="cancelAddGroup" class="btn-secondary">{{ $t('trainingGroupsTab.cancel') }}</button>
            </div>

            <!-- Groups List -->
            <div class="groups-list">
                <div 
                    v-for="group in sortedGroups" 
                    :key="group.id" 
                    class="group-card"
                    :class="{ 'preset-group': group.isPreset }"
                >
                    <div class="group-header">
                        <h4>{{ group.name }}</h4>
                        <div class="group-actions">
                            <button 
                                v-if="!group.isPreset" 
                                @click="editGroup(group)" 
                                class="btn-icon"
                                :title="$t('trainingGroupsTab.edit')"
                            >
                                ✏️
                            </button>
                            <button 
                                v-if="!group.isPreset" 
                                @click="deleteGroup(group)" 
                                class="btn-icon btn-danger"
                                :title="$t('trainingGroupsTab.delete')"
                            >
                                🗑️
                            </button>
                        </div>
                    </div>
                    
                    <div class="group-members">
                        <div class="members-count">
                            {{ group.members ? group.members.length : 0 }} {{ $t('trainingGroupsTab.members') }}
                        </div>
                        <div class="members-list">
                            <span 
                                v-for="member in (group.members || [])" 
                                :key="member.id"
                                class="member-tag"
                            >
                                {{ member.firstName }} {{ member.lastName }}
                                <button 
                                    @click="removeMemberFromGroup(group.id, member.id)"
                                    class="remove-member-btn"
                                    :title="$t('trainingGroupsTab.remove')"
                                >
                                    ×
                                </button>
                            </span>
                        </div>
                    </div>

                    <!-- Add Member to Group -->
                    <div class="add-member-section">
                        <select 
                            v-model="selectedMembers[group.id]"
                            class="member-select"
                            @change="addMemberToGroup(group.id, $event.target.value)"
                            :disabled="availableMembersForGroup(group.id).length === 0"
                        >
                            <option value="">
                                {{ availableMembersForGroup(group.id).length === 0 ? $t('trainingGroupsTab.noMembersAvailable') : $t('trainingGroupsTab.addMember') }}
                            </option>
                            <option 
                                v-for="member in availableMembersForGroup(group.id)" 
                                :key="member.id"
                                :value="member.id"
                            >
                                {{ member.firstName }} {{ member.lastName }}
                            </option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <!-- Edit Group Dialog -->
        <div v-if="editingGroup" class="edit-group-dialog">
            <div class="dialog-content">
                <h3>{{ $t('trainingGroupsTab.editGroup') }}</h3>
                <input 
                    v-model="editingGroup.name" 
                    type="text" 
                    :placeholder="$t('trainingGroupsTab.groupName')"
                    class="input-field"
                />
                <div class="dialog-actions">
                    <button @click="saveGroupEdit" class="btn-primary">{{ $t('common.save') }}</button>
                    <button @click="cancelGroupEdit" class="btn-secondary">{{ $t('trainingGroupsTab.cancel') }}</button>
                </div>
            </div>
        </div>

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

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import { getSafeErrorMessage } from '../utils/errorMessages.js';
import InfoDialog from './InfoDialog.vue';
import ConfirmDialog from './ConfirmDialog.vue';

export default {
    name: 'TrainingGroupsTab',
    components: {
        InfoDialog,
        ConfirmDialog,
    },
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub', 'token']),
        
        sortedGroups() {
            if (!Array.isArray(this.groups)) {
                return [];
            }
            return [...this.groups].sort((a, b) => {
                // Preset-Gruppen zuerst
                if (a.isPreset && !b.isPreset) return -1;
                if (!a.isPreset && b.isPreset) return 1;
                // Dann nach sortOrder
                if (a.sortOrder !== b.sortOrder) return a.sortOrder - b.sortOrder;
                // Dann alphabetisch
                return a.name.localeCompare(b.name);
            });
        },
    },
    data() {
        return {
            groups: [],
            members: [],
            showAddGroupForm: false,
            newGroupName: '',
            editingGroup: null,
            selectedMembers: {},
            infoDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
            },
            confirmDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
                resolveCallback: null,
            },
        };
    },
    async created() {
        if (this.isAuthenticated && this.currentClub) {
            await this.loadGroups();
            await this.loadMembers();
        }
    },
    watch: {
        currentClub() {
            if (this.isAuthenticated && this.currentClub) {
                this.loadGroups();
                this.loadMembers();
            }
        },
    },
    methods: {
        async loadGroups() {
            try {
                const response = await apiClient.get(`/training-groups/${this.currentClub}`);
                // Stelle sicher, dass es ein Array ist und dass jedes Gruppen-Objekt ein members-Array hat
                const groups = Array.isArray(response.data) ? response.data : [];
                this.groups = groups.map(group => ({
                    ...group,
                    members: Array.isArray(group.members) ? group.members : []
                }));
            } catch (error) {
                const msg = getSafeErrorMessage(error, 'Fehler beim Laden der Trainingsgruppen');
                this.showInfo('Fehler', msg, '', 'error');
                this.groups = [];
            }
        },
        
        async loadMembers() {
            try {
                const response = await apiClient.get(`/clubmembers/get/${this.currentClub}/false`);
                const members = Array.isArray(response.data) ? response.data : [];
                // Die API filtert bereits nach active, also müssen wir nicht nochmal filtern
                const filteredMembers = members.filter(m => m != null);
                // Sortiere alphabetisch nach Nachname, dann Vorname
                this.members = filteredMembers.sort((a, b) => {
                    const firstNameA = (a.firstName || '').toLowerCase();
                    const firstNameB = (b.firstName || '').toLowerCase();
                    if (firstNameA !== firstNameB) {
                        return firstNameA.localeCompare(firstNameB);
                    }
                    const lastNameA = (a.lastName || '').toLowerCase();
                    const lastNameB = (b.lastName || '').toLowerCase();
                    return lastNameA.localeCompare(lastNameB);
                });
                console.log('[loadMembers] Loaded', this.members.length, 'active members');
            } catch (error) {
                console.error('[loadMembers] Error:', error);
                const msg = getSafeErrorMessage(error, 'Fehler beim Laden der Mitglieder');
                this.showInfo('Fehler', msg, '', 'error');
                this.members = [];
            }
        },
        
        availableMembersForGroup(groupId) {
            if (!Array.isArray(this.members) || this.members.length === 0) {
                return [];
            }
            const group = this.groups.find(g => g.id === groupId);
            if (!group) {
                return this.members;
            }
            
            const groupMembers = Array.isArray(group.members) ? group.members : [];
            const memberIdsInGroup = new Set(groupMembers.map(m => m && m.id).filter(id => id != null));
            return this.members.filter(m => m && m.id && !memberIdsInGroup.has(m.id));
        },
        
        async createGroup() {
            if (!this.newGroupName.trim()) {
                this.showInfo('Hinweis', 'Bitte geben Sie einen Gruppennamen ein.', '', 'warning');
                return;
            }
            
            try {
                await apiClient.post(`/training-groups/${this.currentClub}`, {
                    name: this.newGroupName.trim(),
                });
                this.newGroupName = '';
                this.showAddGroupForm = false;
                await this.loadGroups();
            } catch (error) {
                const msg = getSafeErrorMessage(error, 'Fehler beim Erstellen der Gruppe');
                this.showInfo('Fehler', msg, '', 'error');
            }
        },
        
        cancelAddGroup() {
            this.newGroupName = '';
            this.showAddGroupForm = false;
        },
        
        editGroup(group) {
            this.editingGroup = { ...group };
        },
        
        async saveGroupEdit() {
            if (!this.editingGroup.name.trim()) {
                this.showInfo('Hinweis', 'Bitte geben Sie einen Gruppennamen ein.', '', 'warning');
                return;
            }
            
            try {
                await apiClient.put(`/training-groups/${this.currentClub}/${this.editingGroup.id}`, {
                    name: this.editingGroup.name.trim(),
                    sortOrder: this.editingGroup.sortOrder,
                });
                this.editingGroup = null;
                await this.loadGroups();
            } catch (error) {
                const msg = getSafeErrorMessage(error, 'Fehler beim Aktualisieren der Gruppe');
                this.showInfo('Fehler', msg, '', 'error');
            }
        },
        
        cancelGroupEdit() {
            this.editingGroup = null;
        },
        
        async deleteGroup(group) {
            const confirmed = await this.showConfirm(
                'Gruppe löschen',
                `Möchten Sie die Gruppe "${group.name}" wirklich löschen?`,
                'Alle Mitglieder-Zuordnungen werden entfernt.',
                'warning'
            );
            
            if (!confirmed) return;
            
            try {
                await apiClient.delete(`/training-groups/${this.currentClub}/${group.id}`);
                await this.loadGroups();
            } catch (error) {
                const msg = getSafeErrorMessage(error, 'Fehler beim Löschen der Gruppe');
                this.showInfo('Fehler', msg, '', 'error');
            }
        },
        
        async addMemberToGroup(groupId, memberId) {
            if (!memberId || !groupId) {
                return;
            }
            
            try {
                await apiClient.post(`/training-groups/${this.currentClub}/${groupId}/member/${memberId}`);
                this.selectedMembers[groupId] = '';
                await this.loadGroups();
            } catch (error) {
                console.error('[addMemberToGroup] Error:', error);
                const msg = getSafeErrorMessage(error, 'Fehler beim Hinzufügen des Mitglieds');
                this.showInfo('Fehler', msg, '', 'error');
            }
        },
        
        async removeMemberFromGroup(groupId, memberId) {
            try {
                await apiClient.delete(`/training-groups/${this.currentClub}/${groupId}/member/${memberId}`);
                await this.loadGroups();
            } catch (error) {
                const msg = getSafeErrorMessage(error, 'Fehler beim Entfernen des Mitglieds');
                this.showInfo('Fehler', msg, '', 'error');
            }
        },
        
        showInfo(title, message, details, type) {
            this.infoDialog = { isOpen: true, title, message, details, type };
        },
        
        showConfirm(title, message, details, type) {
            return new Promise((resolve) => {
                this.confirmDialog = {
                    isOpen: true,
                    title,
                    message,
                    details,
                    type,
                    resolveCallback: resolve,
                };
            });
        },
    },
};
</script>

<style scoped>
.training-groups-tab {
    padding: 1rem 0;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.add-group-form {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 1rem;
    padding: 1rem;
    background: #f5f5f5;
    border-radius: 4px;
}

.input-field {
    flex: 1;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.groups-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1rem;
}

.group-card {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 1rem;
    background: white;
}

.group-card.preset-group {
    border-color: #4CAF50;
    background: #f1f8f4;
}

.group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;
}

.group-header h4 {
    margin: 0;
    color: #333;
}

.group-actions {
    display: flex;
    gap: 0.5rem;
}

.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 1.2rem;
    padding: 0.25rem 0.5rem;
}

.btn-icon:hover {
    opacity: 0.7;
}

.btn-danger {
    color: #d32f2f;
}

.group-members {
    margin-top: 1rem;
}

.members-count {
    font-size: 0.9rem;
    color: #666;
    margin-bottom: 0.5rem;
}

.members-list {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-bottom: 1rem;
}

.member-tag {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.25rem 0.5rem;
    background: #e3f2fd;
    border-radius: 4px;
    font-size: 0.9rem;
}

.remove-member-btn {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 1.2rem;
    line-height: 1;
    color: #d32f2f;
    padding: 0;
    margin-left: 0.25rem;
}

.remove-member-btn:hover {
    opacity: 0.7;
}

.add-member-section {
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #eee;
}

.member-select {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.edit-group-dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.dialog-content {
    background: white;
    padding: 2rem;
    border-radius: 8px;
    min-width: 300px;
}

.dialog-actions {
    display: flex;
    gap: 0.5rem;
    margin-top: 1rem;
    justify-content: flex-end;
}

.btn-primary {
    background: #4CAF50;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
}

.btn-primary:hover {
    background: #45a049;
}

.btn-secondary {
    background: #f5f5f5;
    color: #333;
    border: 1px solid #ddd;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
}

.btn-secondary:hover {
    background: #e0e0e0;
}
</style>

