<template>
    <div class="training-times-tab">
        <div v-if="loading" class="loading">{{ $t('trainingTimesTab.loading') }}</div>
        
        <div v-else class="groups-section">
            <div 
                v-for="group in groups" 
                :key="group.id" 
                class="group-card"
            >
                <div class="group-header">
                    <h3>{{ group.name }}</h3>
                    <div class="group-header-actions">
                        <label class="exclude-quick-diary-label">
                            <input
                                type="checkbox"
                                :checked="Boolean(group.excludeFromQuickDiaryCreate)"
                                @change="onExcludeQuickChange(group, $event)"
                            />
                            <span>{{ $t('trainingTimesTab.excludeFromQuickDiaryCreate') }}</span>
                        </label>
                        <button
                            @click="showAddTimeForm(group.id)"
                            class="btn-primary btn-small"
                        >
                            {{ $t('trainingTimesTab.addTime') }}
                        </button>
                    </div>
                </div>
                
                <!-- Add Time Form -->
                <div v-if="addTimeFormGroupId === group.id" class="add-time-form">
                    <div class="form-row">
                        <label>
                            <span>{{ $t('trainingTimesTab.weekday') }}</span>
                            <select v-model="newTime.weekday" class="input-field">
                                <option :value="0">{{ $t('trainingTimesTab.sunday') }}</option>
                                <option :value="1">{{ $t('trainingTimesTab.monday') }}</option>
                                <option :value="2">{{ $t('trainingTimesTab.tuesday') }}</option>
                                <option :value="3">{{ $t('trainingTimesTab.wednesday') }}</option>
                                <option :value="4">{{ $t('trainingTimesTab.thursday') }}</option>
                                <option :value="5">{{ $t('trainingTimesTab.friday') }}</option>
                                <option :value="6">{{ $t('trainingTimesTab.saturday') }}</option>
                            </select>
                        </label>
                        <label>
                            <span>{{ $t('trainingTimesTab.from') }}</span>
                            <input 
                                v-model="newTime.startTime" 
                                type="time" 
                                class="input-field"
                            />
                        </label>
                        <label>
                            <span>{{ $t('trainingTimesTab.to') }}</span>
                            <input 
                                v-model="newTime.endTime" 
                                type="time" 
                                class="input-field"
                            />
                        </label>
                    </div>
                    <div class="form-actions">
                        <button @click="createTime(group.id)" class="btn-primary">{{ $t('trainingTimesTab.create') }}</button>
                        <button @click="cancelAddTime" class="btn-secondary">{{ $t('trainingTimesTab.cancel') }}</button>
                    </div>
                </div>
                
                <!-- Times List -->
                <div v-if="group.trainingTimes && group.trainingTimes.length > 0" class="times-list">
                    <div 
                        v-for="time in group.trainingTimes" 
                        :key="time.id" 
                        class="time-item"
                    >
                        <div class="time-info">
                            <span class="weekday">{{ getWeekdayName(time.weekday) }}</span>
                            <span class="time-range">{{ formatTime(time.startTime) }} - {{ formatTime(time.endTime) }}</span>
                        </div>
                        <div class="time-actions">
                            <button 
                                @click="editTime(time)" 
                                class="btn-icon"
                                :title="$t('trainingTimesTab.edit')"
                            >
                                ✏️
                            </button>
                            <button 
                                @click="deleteTime(time.id)" 
                                class="btn-icon btn-danger"
                                :title="$t('trainingTimesTab.delete')"
                            >
                                🗑️
                            </button>
                        </div>
                    </div>
                </div>
                <div v-else class="no-times">
                    {{ $t('trainingTimesTab.noTimes') }}
                </div>
            </div>
        </div>
        
        <!-- Edit Time Dialog -->
        <div v-if="editingTime" class="edit-time-dialog">
            <div class="dialog-content">
                <h3>{{ $t('trainingTimesTab.editTime') }}</h3>
                <div class="form-row">
                    <label>
                        <span>{{ $t('trainingTimesTab.weekday') }}</span>
                        <select v-model="editingTime.weekday" class="input-field">
                            <option :value="0">{{ $t('trainingTimesTab.sunday') }}</option>
                            <option :value="1">{{ $t('trainingTimesTab.monday') }}</option>
                            <option :value="2">{{ $t('trainingTimesTab.tuesday') }}</option>
                            <option :value="3">{{ $t('trainingTimesTab.wednesday') }}</option>
                            <option :value="4">{{ $t('trainingTimesTab.thursday') }}</option>
                            <option :value="5">{{ $t('trainingTimesTab.friday') }}</option>
                            <option :value="6">{{ $t('trainingTimesTab.saturday') }}</option>
                        </select>
                    </label>
                    <label>
                        <span>{{ $t('trainingTimesTab.from') }}</span>
                        <input 
                            v-model="editingTime.startTime" 
                            type="time" 
                            class="input-field"
                        />
                    </label>
                    <label>
                        <span>Bis:</span>
                        <input 
                            v-model="editingTime.endTime" 
                            type="time" 
                            class="input-field"
                        />
                    </label>
                </div>
                <div class="form-actions">
                    <button @click="saveTime" class="btn-primary">{{ $t('trainingTimesTab.save') }}</button>
                    <button @click="cancelEdit" class="btn-secondary">{{ $t('trainingTimesTab.cancel') }}</button>
                </div>
            </div>
        </div>
    </div>
</template>

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

export default {
    name: 'TrainingTimesTab',
    computed: {
        ...mapGetters(['currentClub']),
    },
    data() {
        return {
            groups: [],
            loading: false,
            addTimeFormGroupId: null,
            newTime: {
                weekday: 1,
                startTime: '',
                endTime: ''
            },
            editingTime: null
        };
    },
    mounted() {
        this.loadTrainingTimes();
    },
    methods: {
        async loadTrainingTimes() {
            this.loading = true;
            try {
                const response = await apiClient.get(`/training-times/${this.currentClub}`);
                this.groups = Array.isArray(response.data)
                    ? response.data.map((g) => ({
                        ...g,
                        excludeFromQuickDiaryCreate: Boolean(g.excludeFromQuickDiaryCreate),
                    }))
                    : [];
            } catch (error) {
                console.error('[loadTrainingTimes] Error:', error);
                const msg = getSafeErrorMessage(error, 'Fehler beim Laden der Trainingszeiten');
                alert(msg);
                this.groups = [];
            } finally {
                this.loading = false;
            }
        },
        
        async onExcludeQuickChange(group, event) {
            const exclude = Boolean(event.target.checked);
            try {
                await apiClient.put(`/training-groups/${this.currentClub}/${group.id}`, {
                    name: group.name,
                    sortOrder: group.sortOrder,
                    excludeFromQuickDiaryCreate: exclude,
                });
                group.excludeFromQuickDiaryCreate = exclude;
            } catch (error) {
                console.error('[onExcludeQuickChange]', error);
                event.target.checked = !exclude;
                const msg = getSafeErrorMessage(error, this.$t('trainingTimesTab.excludeFromQuickDiarySaveError'));
                alert(msg);
            }
        },

        showAddTimeForm(groupId) {
            this.addTimeFormGroupId = groupId;
            this.newTime = {
                weekday: 1,
                startTime: '',
                endTime: ''
            };
        },
        
        cancelAddTime() {
            this.addTimeFormGroupId = null;
            this.newTime = {
                weekday: 1,
                startTime: '',
                endTime: ''
            };
        },
        
        async createTime(groupId) {
            if (!this.newTime.startTime || !this.newTime.endTime) {
                alert('Bitte füllen Sie alle Felder aus');
                return;
            }
            
            try {
                await apiClient.post(`/training-times/${this.currentClub}`, {
                    trainingGroupId: groupId,
                    weekday: this.newTime.weekday,
                    startTime: this.newTime.startTime,
                    endTime: this.newTime.endTime
                });
                this.cancelAddTime();
                await this.loadTrainingTimes();
            } catch (error) {
                console.error('[createTime] Error:', error);
                const msg = getSafeErrorMessage(error, 'Fehler beim Erstellen der Trainingszeit');
                alert(msg);
            }
        },
        
        editTime(time) {
            this.editingTime = {
                id: time.id,
                weekday: time.weekday,
                startTime: this.formatTimeForInput(time.startTime),
                endTime: this.formatTimeForInput(time.endTime)
            };
        },
        
        cancelEdit() {
            this.editingTime = null;
        },
        
        async saveTime() {
            if (!this.editingTime.startTime || !this.editingTime.endTime) {
                alert('Bitte füllen Sie alle Felder aus');
                return;
            }
            
            try {
                await apiClient.put(`/training-times/${this.currentClub}/${this.editingTime.id}`, {
                    weekday: this.editingTime.weekday,
                    startTime: this.editingTime.startTime,
                    endTime: this.editingTime.endTime
                });
                this.cancelEdit();
                await this.loadTrainingTimes();
            } catch (error) {
                console.error('[saveTime] Error:', error);
                const msg = getSafeErrorMessage(error, this.$t('trainingTimesTab.saveError'));
                alert(msg);
            }
        },
        
        async deleteTime(timeId) {
            if (!confirm('Möchten Sie diese Trainingszeit wirklich löschen?')) {
                return;
            }
            
            try {
                await apiClient.delete(`/training-times/${this.currentClub}/${timeId}`);
                await this.loadTrainingTimes();
            } catch (error) {
                console.error('[deleteTime] Error:', error);
                const msg = getSafeErrorMessage(error, 'Fehler beim Löschen der Trainingszeit');
                alert(msg);
            }
        },
        
        getWeekdayName(weekday) {
            const days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
            const i = Number(weekday);
            return days[i] || '';
        },
        
        formatTime(time) {
            if (!time) return '';
            // Time comes as HH:MM:SS or HH:MM, we want HH:MM
            return time.substring(0, 5);
        },
        
        formatTimeForInput(time) {
            if (!time) return '';
            // Ensure format HH:MM for time input
            return time.substring(0, 5);
        }
    }
};
</script>

<style scoped>
.training-times-tab {
    padding: 20px;
}

.loading {
    text-align: center;
    padding: 40px;
    color: #666;
}

.groups-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.group-card {
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 16px;
}

.group-header {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 16px;
}

.group-header-actions {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px;
}

.exclude-quick-diary-label {
    display: inline-flex;
    align-items: flex-start;
    gap: 8px;
    font-size: 0.85rem;
    color: #444;
    cursor: pointer;
    margin: 0;
    max-width: 22rem;
    line-height: 1.35;
}

.exclude-quick-diary-label input {
    margin-top: 0.2rem;
    flex-shrink: 0;
}

.group-header h3 {
    margin: 0;
    font-size: 1.2rem;
}

.btn-small {
    padding: 6px 12px;
    font-size: 0.9rem;
}

.add-time-form {
    background: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 16px;
}

.form-row {
    display: flex;
    gap: 12px;
    margin-bottom: 12px;
    flex-wrap: wrap;
}

.form-row label {
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex: 1;
    min-width: 150px;
}

.form-row span {
    font-size: 0.9rem;
    color: #666;
}

.input-field {
    padding: 6px 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 0.9rem;
}

.form-actions {
    display: flex;
    gap: 8px;
}

.times-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.time-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    background: #f9f9f9;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
}

.time-info {
    display: flex;
    gap: 16px;
    align-items: center;
}

.weekday {
    font-weight: 600;
    min-width: 100px;
}

.time-range {
    color: #666;
}

.time-actions {
    display: flex;
    gap: 8px;
}

.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 1.2rem;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background 0.2s;
}

.btn-icon:hover {
    background: #f0f0f0;
}

.btn-danger:hover {
    background: #fee;
}

.no-times {
    color: #999;
    font-style: italic;
    padding: 20px;
    text-align: center;
}

.edit-time-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: #fff;
    border-radius: 8px;
    padding: 24px;
    max-width: 500px;
    width: 90%;
}

.dialog-content h3 {
    margin: 0 0 20px 0;
}

.btn-primary {
    background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
    color: var(--text-on-primary);
    border: 1px solid transparent;
    padding: 8px 16px;
    border-radius: 10px;
    cursor: pointer;
    font-size: 0.9rem;
    font-weight: 600;
}

.btn-primary:hover {
    opacity: 0.95;
}

.btn-secondary {
    background: #6c757d;
    color: #fff;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
}

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