<template>
    <div>
        <h2>Spielpläne</h2>
        <button @click="openImportModal">Spielplanimport</button>
        <div v-if="hoveredMatch" class="hover-info">
            <p><strong>{{ hoveredMatch.location.name }}</strong></p>
            <p>{{ hoveredMatch.location.address }}</p>
            <p>{{ hoveredMatch.location.zip }} {{ hoveredMatch.location.city }}</p>
        </div>
        <div class="output">
            <ul>
                <li v-for="league in leagues" :key="league" @click="loadMatchesForLeague(league.id, league.name)">{{
                    league.name }}</li>
            </ul>
            <div class="flex-item">
                <button @click="generatePDF">Download PDF</button>
                <div v-if="matches.length > 0">
                    <h3>Spiele für {{ selectedLeague }}</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>Datum</th>
                                <th>Uhrzeit</th>
                                <th>Heimmannschaft</th>
                                <th>Gastmannschaft</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="match in matches" :key="match.id" @mouseover="hoveredMatch = match"
                                @mouseleave="hoveredMatch = null">
                                <td>{{ formatDate(match.date) }}</td>
                                <td>{{ match.time.toString().slice(0, 5) }} Uhr</td>
                                <td v-html="highlightClubName(match.homeTeam.name)"></td>
                                <td v-html="highlightClubName(match.guestTeam.name)"></td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div v-else>
                    <p>Keine Spiele vorhanden</p>
                </div>
            </div>
        </div>

        <div v-if="showImportModal" class="modal">
            <div class="modal-content">
                <span class="close" @click="closeImportModal">&times;</span>
                <h3>Spielplan importieren</h3>
                <form @submit.prevent="importCSV">
                    <label for="csvFile">CSV-Datei hochladen:</label>
                    <input type="file" id="csvFile" @change="onFileSelected" accept=".csv" required />
                    <button type="submit">Importieren</button>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import PDFGenerator from '../components/PDFGenerator.js';

export default {
    name: 'ScheduleView',
    computed: {
        ...mapGetters(['isAuthenticated', 'currentClub', 'clubs', 'currentClubName']),
    },
    data() {
        return {
            showImportModal: false,
            selectedFile: null,
            leagues: [],
            matches: [],
            selectedLeague: '',
            hoveredMatch: null,
        };
    },
    methods: {
        openImportModal() {
            this.showImportModal = true;
        },
        closeImportModal() {
            this.showImportModal = false;
            this.selectedFile = null;
        },
        onFileSelected(event) {
            this.selectedFile = event.target.files[0];
        },
        async importCSV() {
            if (!this.selectedFile) return;

            const formData = new FormData();
            formData.append('file', this.selectedFile);
            formData.append('clubId', this.currentClub);

            try {
                const response = await apiClient.post('/matches/import', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                alert('Spielplan erfolgreich importiert!');
                this.closeImportModal();
                this.loadLeagues();
            } catch (error) {
                console.error('Fehler beim Importieren der CSV:', error);
                alert('Fehler beim Importieren der CSV.');
            }
        },
        async loadLeagues() {
            try {
                const clubId = this.currentClub;
                const response = await apiClient.get(`/matches/leagues/current/${clubId}`);
                this.leagues = response.data;
            } catch (error) {
                console.error('Failed to load leagues:', error);
            }
        },
        async loadMatchesForLeague(leagueId, leagueName) {
            this.selectedLeague = leagueName;
            try {
                const response = await apiClient.get(`/matches/leagues/${this.currentClub}/matches/${leagueId}`);
                this.matches = response.data;
            } catch (error) {
                console.error('Failed to load matches:', error);
                this.matches = [];
            }
        },
        formatDate(date) {
            const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
            return new Date(date).toLocaleDateString('de-DE', options);
        },
        highlightClubName(teamName) {
            const clubName = this.currentClubName;
            if (clubName && teamName.includes(clubName)) {
                return `<strong>${teamName}</strong>`;
            }
            return teamName;
        },
        getCurrentClubName() {
            const club = this.clubs.find(club => club.id === this.currentClub);
            return club ? club.name : '';
        },
        async generatePDF() {
            const element = this.$el.querySelector('.flex-item > div');
            if (element) {
                const pdfGen = new PDFGenerator();
                await pdfGen.addSchedule(element);
                pdfGen.addNewPage();
                pdfGen.addHeader('Hallen-Adressen');
                const uniqueLocations = this.getUniqueLocations();
                uniqueLocations.forEach((addressLines, clubName) => {
                    pdfGen.addAddress(clubName, addressLines);
                });

                pdfGen.save('Spielpläne.pdf');
            } else {
                console.error('No matches found to generate PDF.');
            }
        },
        getUniqueLocations() {
            const uniqueLocations = new Map();
            this.matches.forEach(match => {
                const location = match.location;
                const clubName = match.homeTeam.name;
                const addressLines = [
                    location.name,
                    location.address,
                    `${location.zip} ${location.city}`
                ];
                const addressKey = addressLines.join('; ');
                if (!uniqueLocations.has(addressKey)) {
                    uniqueLocations.set(clubName, addressLines);
                }
            });

            return uniqueLocations;
        }
    },
    async created() {
        await this.loadLeagues();
    }
};
</script>

<style scoped>
.output {
    display: flex;
}

.output ul {
    flex: 0;
    margin-right: 20px;
}

.flex-item {
    flex: 1;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

table,
th,
td {
    border: 1px solid #ddd;
    padding: 8px;
}

th {
    background-color: #f2f2f2;
    text-align: left;
}

tr:hover {
    background-color: #f5f5f5;
}

th,
td {
    white-space: nowrap;
}

.hover-info {
    margin-top: 10px;
    background-color: #eef;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    max-width: 300px;
    position: fixed;
    top: 16em;
    left: 14em;
}

.modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.8);
}

.modal-content {
    background-color: #fefefe;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 500px;
    max-height: 80%;
    box-shadow: 4px 3px 2px #999;
    position: relative;
}

.close {
    position: absolute;
    top: 10px;
    right: 15px;
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

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

li {
    white-space: nowrap;
    color: #45a049;
    cursor: pointer;
}
</style>
