<script lang="ts">
    import { onMount } from 'svelte';
    import { QualifierEvent_LeaderboardSort, Map } from 'moons-ta-client';
    import type { BeatSaverMap } from '$lib/services/beatsaver';
    import { createEventDispatcher } from "svelte";
    import { saveAs } from 'file-saver';
    import * as XLSX from 'xlsx';

    interface Score {
        accuracy: number;
        badCuts: number;
        color: string;
        eventId: string;
        fullCombo: boolean;
        goodCuts: number;
        isPlaceholder: boolean;
        mapId: string;
        maxCombo: number;
        maxPossibleScore: number;
        modifiedScore: number;
        multipliedScore: number;
        notesMissed: number;
        platformId: string;
        username: string;
    }

    interface CustomMap {
        taData: Map,
        beatsaverData: BeatSaverMap
    }

    const dispatch = createEventDispatcher();

    export let scores: Score[] = [];
    export let mapData: CustomMap | null;
    export let sortType: QualifierEvent_LeaderboardSort = QualifierEvent_LeaderboardSort.ModifiedScore;

    // Export type definition
    type ExportType = 'json' | 'csv' | 'excel' | 'txt';
    let selectedExportType: ExportType = 'json';
    let showExportDropdown = false;

    let currentPage = 1;
    let itemsPerPage = 10;
    let searchQuery = "";

    $: filteredScores = scores.filter(score => 
        score.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
        score.platformId.includes(searchQuery)
    );

    $: totalPages = Math.ceil(filteredScores.length / itemsPerPage);
    $: paginatedScores = filteredScores.slice(
        (currentPage - 1) * itemsPerPage,
        currentPage * itemsPerPage
    );

    $: startIndex = (currentPage - 1) * itemsPerPage;

    function formatAccuracy(accuracy: number): string {
        return (accuracy * 100).toFixed(2) + '%';
    }

    function formatScore(score: number): string {
        return score.toLocaleString();
    }

    function goToPage(page: number) {
        if (page >= 1 && page <= totalPages) {
            currentPage = page;
        }
    }

    function getPaginationPages(): number[] {
        const pages: number[] = [];
        const maxVisible = 5;
        
        if (totalPages <= maxVisible) {
            for (let i = 1; i <= totalPages; i++) {
                pages.push(i);
            }
        } else {
            const half = Math.floor(maxVisible / 2);
            let start = Math.max(1, currentPage - half);
            let end = Math.min(totalPages, start + maxVisible - 1);
            
            if (end - start + 1 < maxVisible) {
                start = Math.max(1, end - maxVisible + 1);
            }
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
        }
        
        return pages;
    }

    function formatLeaderboardData() {
        return scores.map(score => ({
            playerUsername: score.username,
            playerPlatformId: score.platformId,
            score: score.modifiedScore,
            accuracy: score.accuracy,
            misses: score.notesMissed,
            badCuts: score.badCuts,
            isFC: score.fullCombo,
            multipliedScore: score.multipliedScore,
            maxCombo: score.maxCombo,
            goodCuts: score.goodCuts,
            maxScore: score.maxPossibleScore
        }));
    }

    // Export functions
    function exportJSON() {
        const data = formatLeaderboardData();
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        saveAs(blob, `${mapData!.taData.gameplayParameters!.beatmap!.name}_qualifier_scores.json`);
    }

    function exportCSV() {
        const data = formatLeaderboardData();
        const headers = Object.keys(data[0]).join(',');
        const rows = data.map(x => Object.values(x).join(','));
        const csv = [headers, ...rows].join('\n');
        const blob = new Blob([csv], { type: 'text/csv' });
        saveAs(blob, `${mapData!.taData.gameplayParameters!.beatmap!.name}_qualifier_scores.csv`);
    }

    function exportExcel() {
        const data = formatLeaderboardData();
        const worksheet = XLSX.utils.json_to_sheet(data);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Scores');
        XLSX.writeFile(workbook, `${mapData!.taData.gameplayParameters!.beatmap!.name}_qualifier_scores.xlsx`);
    }

    function exportTXT() {
        const data = formatLeaderboardData();
        const text = data.map(x =>
            Object.entries(x)
                .map(([key, value]) => `${key}: ${value}`)
                .join('\n')
        ).join('\n\n');
        const blob = new Blob([text], { type: 'text/plain' });
        saveAs(blob, `${mapData!.taData.gameplayParameters!.beatmap!.name}_qualifier_scores.txt`);
    }

    function handleExport() {
        switch(selectedExportType) {
            case 'json': exportJSON(); break;
            case 'csv': exportCSV(); break;
            case 'excel': exportExcel(); break;
            case 'txt': exportTXT(); break;
        }
        showExportDropdown = false;
    }

    function closePopup() {
        dispatch('close')
    }

    function handleKeydown(event: KeyboardEvent) {
        if (event.key === 'Escape') {
            closePopup();
        }
    }
</script>

<!-- svelte-ignore missing-declaration -->
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div class="popup-overlay" on:click={closePopup} on:keydown={handleKeydown} role="dialog" aria-modal="true">
        <!-- svelte-ignore missing-declaration -->
        <!-- svelte-ignore a11y-click-events-have-key-events -->
        <div class="popup-content" on:click|stopPropagation>
            <button class="close-button" on:click={closePopup} aria-label="Close leaderboard">
                <span class="material-icons">close</span>
            </button>
        <div class="leaderboard-container">
            <div class="leaderboard-header">
                <div class="map-info">
                    {#if mapData?.beatsaverData.metadata.songName}
                        <div class="map-image">
                            <img src={mapData.beatsaverData.versions[0].coverURL} alt={mapData?.beatsaverData.metadata.songName} />
                        </div>
                    {/if}
                    <div class="map-details">
                        <h2>{mapData?.beatsaverData.metadata.songName}</h2>
                        <p class="sort-type">Sorted by: {QualifierEvent_LeaderboardSort[sortType]}</p>
                    </div>
                </div>

                <div class="export-dropdown">
                    <button
                        class="btn export-btn"
                        class:disabled={scores.length === 0}
                        on:click={() => showExportDropdown = !showExportDropdown}
                        disabled={scores.length === 0}
                    >
                        <span class="material-symbols-outlined">download</span>
                        <span>Export Scores</span>
                    </button>
                    {#if showExportDropdown}
                        <div class="dropdown-content">
                            <select bind:value={selectedExportType} class="export-select">
                                <option value="json">JSON</option>
                                <option value="csv">CSV</option>
                                <option value="excel">Excel</option>
                                <option value="txt">Text</option>
                            </select>
                            <button class="export-action-btn" on:click={handleExport}>
                                Export Scores
                            </button>
                        </div>
                    {/if}
                </div>
                
                <div class="search-container">
                    <span class="material-icons search-icon">search</span>
                    <input 
                        type="text" 
                        placeholder="Search players..." 
                        bind:value={searchQuery}
                        class="search-input"
                    />
                </div>
            </div>

            <div class="leaderboard-content">
                <div class="leaderboard-table">
                    <div class="table-header">
                        <div class="rank-col">Rank</div>
                        <div class="player-col">Player</div>
                        <div class="score-col">Score</div>
                        <div class="accuracy-col">Accuracy</div>
                        <div class="combo-col">Cuts & Max Combo</div>
                        <div class="status-col">Full Combo</div>
                    </div>

                    {#each paginatedScores as score, index}
                        <div class="table-row" style="--player-color: {score.color}">
                            <div class="rank-col">
                                <div class="rank-number">#{startIndex + index + 1}</div>
                            </div>
                            <div class="player-col">
                                <div class="player-info">
                                    <div class="player-name" style="color: {score.color}">{score.username}</div>
                                    <div class="player-id">{score.platformId}</div>
                                </div>
                            </div>
                            <div class="score-col">
                                <div class="score-value">{formatScore(score.modifiedScore)}</div>
                                <div class="score-max">/ {formatScore(score.maxPossibleScore)}</div>
                            </div>
                            <div class="accuracy-col">
                                <div class="accuracy-value">{formatAccuracy(score.accuracy)}</div>
                            </div>
                            <div class="combo-col">
                                <div class="combo-value">{score.maxCombo}</div>
                                <div class="combo-details">
                                    <span class="good-cuts">{score.goodCuts} good</span>
                                    {#if score.badCuts > 0}
                                        <span class="bad-cuts">{score.badCuts} bad</span>
                                    {/if}
                                    {#if score.notesMissed > 0}
                                        <span class="missed-notes">{score.notesMissed} missed</span>
                                    {/if}
                                </div>
                            </div>
                            <div class="status-col">
                                {#if score.fullCombo}
                                    <div class="status-badge full-combo">
                                        <span class="material-icons">star</span>
                                        Full Combo
                                    </div>
                                {:else}
                                    <div class="status-badge incomplete">
                                        <span class="material-icons">remove_circle</span>
                                        Not FC
                                    </div>
                                {/if}
                            </div>
                        </div>
                    {/each}

                    {#if paginatedScores.length === 0}
                        <div class="no-results">
                            <span class="material-icons">search_off</span>
                            <p>No players found matching your search.</p>
                        </div>
                    {/if}
                </div>

                {#if totalPages > 1}
                    <div class="pagination">
                        <button 
                            class="pagination-btn" 
                            disabled={currentPage === 1}
                            on:click={() => goToPage(currentPage - 1)}
                        >
                            <span class="material-icons">chevron_left</span>
                        </button>

                        {#each getPaginationPages() as page}
                            <button 
                                class="pagination-btn {currentPage === page ? 'active' : ''}"
                                on:click={() => goToPage(page)}
                            >
                                {page}
                            </button>
                        {/each}

                        <button 
                            class="pagination-btn" 
                            disabled={currentPage === totalPages}
                            on:click={() => goToPage(currentPage + 1)}
                        >
                            <span class="material-icons">chevron_right</span>
                        </button>

                        <div class="pagination-info">
                            Page {currentPage} of {totalPages} ({filteredScores.length} players)
                        </div>
                    </div>
                {/if}
            </div>
        </div>
    </div>
</div>

<style>
    .btn {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        background-color: var(--button-bg);
        color: var(--text);
        border: none;
        border-radius: 6px;
        padding: 0.625rem 1rem;
        font-size: 0.875rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .btn:hover {
        background-color: var(--button-hover-bg);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }

    .export-btn {
        background-color: var(--comfortable-blue);
        color: white;
        position: relative;
        box-shadow: 0 0 10px rgb(71, 73, 202);
    }

    .export-btn:hover:not(.disabled) {
        background-color: rgb(71, 73, 202);
        border-color: rgba(255, 255, 255, 0.2);
    }

    .export-btn.disabled {
        background-color: #4a4a4a;
        color: #888888;
        cursor: not-allowed;
        opacity: 0.6;
        transform: none;
        box-shadow: none;
    }

    .export-dropdown {
        position: relative;
        z-index: 100;
    }

    .dropdown-content {
        position: absolute;
        top: calc(100% + 8px);
        right: 0;
        background-color: var(--bg-secondary);
        border: 2px solid #4fc3f7;
        border-radius: 8px;
        padding: 1rem;
        z-index: 1001;
        min-width: 200px;
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 0 20px rgba(79, 195, 247, 0.3);
        animation: dropdownSlide 0.2s ease-out;
    }

    @keyframes dropdownSlide {
        from {
            opacity: 0;
        }
        to {
            opacity: 1;
        }
    }

    .dropdown-content::before {
        content: '';
        position: absolute;
        top: -10px;
        right: 16px;
        width: 0;
        height: 0;
        border-left: 8px solid transparent;
        border-right: 8px solid transparent;
        border-bottom: 8px solid #4fc3f7;
    }

    .export-select {
        background-color: var(--bg-secondary);
        color: var(--text);
        border: 1px solid #555;
        border-radius: 6px;
        padding: 0.5rem 0.75rem;
        font-size: 0.875rem;
        width: 100%;
        cursor: pointer;
        transition: all 0.2s ease;
        outline: none;
    }

    .export-select:hover {
        border-color: #4fc3f7;
        background-color: rgba(79, 195, 247, 0.05);
    }

    .export-select:focus {
        border-color: #4fc3f7;
        box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.2);
        background-color: rgba(79, 195, 247, 0.05);
    }

    .export-action-btn {
        background-color: var(--pick-green);
        color: white;
        border: none;
        border-radius: 6px;
        padding: 0.5rem 1rem;
        font-size: 0.875rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .export-action-btn:hover {
        background-color: var(--pick-green-hover);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }

    .export-action-btn:active {
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .popup-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.75);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
        padding: 1rem;
        backdrop-filter: blur(4px);
    }

    .popup-content {
        position: relative;
        max-width: 95vw;
        max-height: 95vh;
        overflow: auto;
        border-radius: 0.75rem;
    }

    .close-button {
        position: absolute;
        top: 1rem;
        right: 1rem;
        width: 2.5rem;
        height: 2.5rem;
        border: none;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.2);
        color: white;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1001;
        transition: background-color 0.2s;
        backdrop-filter: blur(10px);
    }

    .close-button:hover {
        background-color: rgba(255, 255, 255, 0.3);
    }

    .close-button .material-icons {
        font-size: 1.25rem;
    }

    .leaderboard-container {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        max-width: 100%;
        width: 100%;
    }

    .leaderboard-header {
        background: linear-gradient(135deg, var(--accent-color), var(--accent-hover));
        padding: 2rem;
        color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 1.5rem;
    }

    .map-info {
        display: flex;
        align-items: center;
        gap: 1.5rem;
    }

    .map-image {
        width: 4rem;
        height: 4rem;
        border-radius: 0.5rem;
        overflow: hidden;
        flex-shrink: 0;
    }

    .map-image img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .map-details h2 {
        margin: 0 0 0.5rem 0;
        font-size: 1.5rem;
        font-weight: 600;
    }

    .sort-type {
        margin: 0;
        opacity: 0.9;
        font-size: 0.875rem;
    }

    .search-container {
        position: relative;
        display: flex;
        align-items: center;
        margin-right: 2rem;
    }

    .search-icon {
        position: absolute;
        left: 1rem;
        color: var(--text-secondary);
        z-index: 1;
    }

    .search-input {
        padding: 0.75rem 1rem 0.75rem 3rem;
        border: none;
        border-radius: 0.5rem;
        background-color: rgba(255, 255, 255, 0.1);
        color: white;
        font-size: 0.875rem;
        width: 300px;
        backdrop-filter: blur(10px);
    }

    .search-input::placeholder {
        color: rgba(255, 255, 255, 0.7);
    }

    .search-input:focus {
        outline: none;
        background-color: rgba(255, 255, 255, 0.2);
    }

    .leaderboard-content {
        padding: 0;
    }

    .leaderboard-table {
        width: 100%;
    }

    .table-header {
        display: grid;
        grid-template-columns: 80px 1fr 150px 120px 140px 140px;
        gap: 1rem;
        padding: 1.5rem 2rem;
        background-color: var(--bg-secondary);
        border-bottom: 1px solid var(--border-color);
        font-weight: 600;
        font-size: 0.875rem;
        color: var(--text-secondary);
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    .table-row {
        display: grid;
        grid-template-columns: 80px 1fr 150px 120px 140px 140px;
        gap: 1rem;
        padding: 1.5rem 2rem;
        border-bottom: 1px solid var(--border-color);
        transition: background-color 0.2s;
        align-items: center;
    }

    .table-row:hover {
        background-color: var(--bg-secondary);
    }

    .rank-number {
        font-weight: 600;
        font-size: 1.125rem;
        color: var(--text-primary);
    }

    .player-info {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }

    .player-name {
        font-weight: 600;
        font-size: 1rem;
    }

    .player-id {
        font-size: 0.75rem;
        color: var(--text-secondary);
        font-family: monospace;
    }

    .score-value {
        font-weight: 600;
        font-size: 1.125rem;
        color: var(--text-primary);
    }

    .score-max {
        font-size: 0.75rem;
        color: var(--text-secondary);
    }

    .accuracy-value {
        font-weight: 600;
        font-size: 1rem;
        color: var(--success-color);
    }

    .combo-value {
        font-weight: 600;
        font-size: 1rem;
        color: var(--text-primary);
    }

    .combo-details {
        display: flex;
        flex-direction: column;
        gap: 0.125rem;
        font-size: 0.75rem;
    }

    .good-cuts {
        color: var(--success-color);
    }

    .bad-cuts {
        color: var(--error-color);
    }

    .missed-notes {
        color: var(--warning-color);
    }

    .status-badge {
        display: flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.375rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .status-badge.full-combo {
        background-color: rgba(34, 197, 94, 0.1);
        color: var(--success-color);
    }

    .status-badge.incomplete {
        background-color: rgba(239, 68, 68, 0.1);
        color: var(--error-color);
    }

    .status-badge .material-icons {
        font-size: 1rem;
    }

    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0.5rem;
        padding: 2rem;
        border-top: 1px solid var(--border-color);
        background-color: var(--bg-secondary);
    }

    .pagination-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 2.5rem;
        height: 2.5rem;
        border: none;
        border-radius: 0.375rem;
        background-color: var(--bg-primary);
        color: var(--text-primary);
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
        border: 1px solid var(--border-color);
    }

    .pagination-btn:hover:not(:disabled) {
        background-color: var(--accent-color);
        color: white;
        border-color: var(--accent-color);
    }

    .pagination-btn.active {
        background-color: var(--accent-color);
        color: white;
        border-color: var(--accent-color);
    }

    .pagination-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .pagination-info {
        margin-left: 1rem;
        font-size: 0.875rem;
        color: var(--text-secondary);
    }

    .no-results {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 4rem 2rem;
        color: var(--text-secondary);
        text-align: center;
    }

    .no-results .material-icons {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    .no-results p {
        margin: 0;
        font-size: 1.125rem;
    }

    @media (max-width: 768px) {
        .leaderboard-header {
            flex-direction: column;
            align-items: stretch;
        }

        .search-input {
            width: 100%;
        }

        .table-header,
        .table-row {
            grid-template-columns: 60px 1fr 100px 80px;
            gap: 0.5rem;
            padding: 1rem;
        }

        .combo-col,
        .status-col {
            display: none;
        }

        .map-info {
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .pagination {
            flex-wrap: wrap;
            gap: 0.25rem;
        }

        .pagination-info {
            margin-left: 0;
            margin-top: 0.5rem;
            width: 100%;
            text-align: center;
        }
    }
</style>