<script lang="ts">
    import { createEventDispatcher } from 'svelte';
    import { type Map, GameplayModifiers_GameOptions } from 'moons-ta-client';
    import type { BeatSaverMap } from '$lib/services/beatsaver.js';

    interface CustomMap {
        taData: Map,
        beatsaverData: BeatSaverMap
    }

    export let maps: CustomMap[] = [];

    const dispatch = createEventDispatcher();

    enum MapDifficulty {
        "Easy" = 0,
        "Normal" = 1,
        "Hard" = 2,
        "Expert" = 3,
        "Expert+" = 4
    }

    const modifierNameMap: Record<number, string> = {
        [GameplayModifiers_GameOptions.None]: "",
        [GameplayModifiers_GameOptions.NoFail]: "No Fail",
        [GameplayModifiers_GameOptions.NoBombs]: "No Bombs",
        [GameplayModifiers_GameOptions.NoArrows]: "No Arrows",
        [GameplayModifiers_GameOptions.NoObstacles]: "No Walls",
        [GameplayModifiers_GameOptions.SlowSong]: "Slower Song",
        [GameplayModifiers_GameOptions.InstaFail]: "One Life",
        [GameplayModifiers_GameOptions.FailOnClash]: "Fail on Clash",
        [GameplayModifiers_GameOptions.BatteryEnergy]: "Four Lives",
        [GameplayModifiers_GameOptions.FastNotes]: "Fast Notes",
        [GameplayModifiers_GameOptions.FastSong]: "Faster Song",
        [GameplayModifiers_GameOptions.DisappearingArrows]: "Disappearing Arrows",
        [GameplayModifiers_GameOptions.GhostNotes]: "Ghost Notes",
        [GameplayModifiers_GameOptions.DemoNoFail]: "Demo No Fail",
        [GameplayModifiers_GameOptions.DemoNoObstacles]: "Demo No Obstacles",
        [GameplayModifiers_GameOptions.StrictAngles]: "Strict Angles",
        [GameplayModifiers_GameOptions.ProMode]: "Pro Mode",
        [GameplayModifiers_GameOptions.ZenMode]: "Zen Mode",
        [GameplayModifiers_GameOptions.SmallCubes]: "Small Notes",
        [GameplayModifiers_GameOptions.SuperFastSong]: "Super Fast Song"
    };

    let showConfirmDialog = false;
    let mapToLoad: CustomMap | null = null;

    function handleAddMap() {
        dispatch('addMap');
    }

    function handleEditMap(map: CustomMap) {
        dispatch('editMap', { map: map });
    }

    function handleRemoveMap(map: CustomMap) {
        dispatch('removeMap', { map: map });
    }

    function handleAddMapsFromTAPool() {
        dispatch('addMapsFromTAPool');
    }

    function handleLoadMap(map: CustomMap) {
        mapToLoad = map;
        showConfirmDialog = true;
    }

    function handleMapClick(map: CustomMap) {
        handleLoadMap(map);
    }

    function confirmLoad() {
        if (mapToLoad) {
            dispatch('songLoad', { map: mapToLoad });
            showConfirmDialog = false;
            mapToLoad = null;
        }
    }

    function cancelLoad() {
        showConfirmDialog = false;
        mapToLoad = null;
    }

    function getActiveModifiersCompact(gameplayModifiers: number): string[] {
        const activeModifiers: string[] = [];
        const values = Object.values(GameplayModifiers_GameOptions)
            .filter((value): value is number => 
                typeof value === 'number' && 
                value !== GameplayModifiers_GameOptions.None &&
                value > 0
            )
            .sort((a, b) => a - b);
        
        for (const value of values) {
            if ((gameplayModifiers & value) === value) {
                const name = modifierNameMap[value];
                if (name && name.trim() !== "") {
                    activeModifiers.push(name);
                }
            }
        }
        
        return activeModifiers;
    }

    function getModifierArray(map: CustomMap): string[] {
        if (map.taData.gameplayParameters?.gameplayModifiers?.options == 0) {
            return [];
        }
        return getActiveModifiersCompact(map.taData.gameplayParameters?.gameplayModifiers?.options || 0);
    }

    function getDifficultyName(difficulty: number): string {
        return MapDifficulty[difficulty] || 'Unknown';
    }
</script>

<div class="song-queue">
    <div class="queue-header">
        <h3>Song Queue ({maps.length})</h3>
        <button class="action-button add-map" on:click={handleAddMap}>
            <span class="material-icons">add</span>
            Add Map
        </button>
        <button class="action-button add-map" on:click={handleAddMapsFromTAPool}>
            <span class="material-icons">add</span>
            Add Maps From TA Pool
        </button>
    </div>

    {#if maps.length === 0}
        <div class="empty-state">
            <span class="material-icons">queue_music</span>
            <p>No maps in queue</p>
            <p class="empty-subtitle">Add maps to get started</p>
        </div>
    {:else}
        <div class="maps-list">
            {#each maps as map, index (map.taData.guid)}
                <div class="map-card" on:click={() => handleMapClick(map)} on:keydown={(e) => e.key === 'Enter' && handleMapClick(map)} tabindex="0" role="button">
                    <div class="map-index">
                        {index + 1}
                    </div>
                    <div class="map-cover">
                        <img 
                            src={map.beatsaverData.versions[0]?.coverURL || '/default-song-cover.png'} 
                            alt="Map Cover" 
                        />
                    </div>
                    <div class="map-info">
                        <h4 class="map-title">{map.beatsaverData.name || 'Unknown Song'}</h4>
                        <p class="map-artist">{map.beatsaverData.metadata?.songAuthorName || 'Unknown Artist'}</p>
                        <div class="map-details">
                            <span class="difficulty-badge difficulty-{map.taData.gameplayParameters?.beatmap?.difficulty}">
                                {getDifficultyName(map.taData.gameplayParameters?.beatmap?.difficulty || 0)}
                            </span>
                            {#if getModifierArray(map).length > 0}
                                <div class="modifiers">
                                    {#each getModifierArray(map) as modifier}
                                        <span class="modifier-tag">{modifier}</span>
                                    {/each}
                                </div>
                            {/if}
                        </div>
                    </div>
                    <!-- svelte-ignore a11y-no-static-element-interactions -->
                    <div class="map-actions" on:click|stopPropagation on:keydown|stopPropagation>
                        <button 
                            class="action-button load-map" 
                            on:click={() => handleLoadMap(map)}
                            title="Load Map"
                        >
                            <span class="material-icons">play_arrow</span>
                        </button>
                        <button 
                            class="action-button edit-map" 
                            on:click={() => handleEditMap(map)}
                            title="Edit Map"
                        >
                            <span class="material-icons">edit</span>
                        </button>
                        <button 
                            class="action-button remove-map" 
                            on:click={() => handleRemoveMap(map)}
                            title="Remove Map"
                        >
                            <span class="material-icons">delete</span>
                        </button>
                    </div>
                </div>
            {/each}
        </div>
    {/if}
</div>

<!-- Confirmation Dialog -->
{#if showConfirmDialog}
    <!-- svelte-ignore a11y-no-static-element-interactions -->
    <div class="dialog-overlay" on:click={cancelLoad} on:keydown={(e) => e.key === 'Escape' && cancelLoad()}>
        <div class="dialog" on:click|stopPropagation on:keydown|stopPropagation>
            <div class="dialog-header">
                <h3>Load Map</h3>
                <button class="dialog-close" on:click={cancelLoad}>
                    <span class="material-icons">close</span>
                </button>
            </div>
            <div class="dialog-content">
                <p>Are you sure you want to load this map for all players in the match?</p>
                {#if mapToLoad}
                    <div class="map-preview">
                        <img 
                            src={mapToLoad.beatsaverData.versions[0]?.coverURL || '/default-song-cover.png'} 
                            alt="Map Cover"
                            class="preview-cover"
                        />
                        <div class="preview-info">
                            <h4>{mapToLoad.beatsaverData.name || 'Unknown Song'}</h4>
                            <p>{mapToLoad.beatsaverData.metadata?.songAuthorName || 'Unknown Artist'}</p>
                            <span class="difficulty-badge difficulty-{mapToLoad.taData.gameplayParameters?.beatmap?.difficulty}">
                                {getDifficultyName(mapToLoad.taData.gameplayParameters?.beatmap?.difficulty || 0)}
                            </span>
                        </div>
                    </div>
                {/if}
            </div>
            <div class="dialog-actions">
                <button class="action-button cancel-button" on:click={cancelLoad}>Cancel</button>
                <button class="action-button confirm-button" on:click={confirmLoad}><span class="material-icons">play_arrow</span> Load Map</button>
            </div>
        </div>
    </div>
{/if}

<style>
    .song-queue {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        padding: 1.5rem;
        height: fit-content;
    }

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

    .queue-header h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin: 0;
        color: var(--text-primary);
    }

    .action-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        border: none;
        font-size: 0.875rem;
    }

    .action-button.add-map {
        background-color: var(--accent-color);
        color: white;
    }

    .action-button.add-map:hover {
        background-color: var(--accent-hover);
        box-shadow: 0 0 10px var(--accent-glow);
    }

    .action-button.load-map {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
        padding: 0.375rem;
    }

    .action-button.load-map:hover {
        background-color: var(--accent-color);
        color: white;
        box-shadow: 0 0 10px var(--accent-glow);
    }

    .action-button.edit-map {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
        padding: 0.375rem;
    }

    .action-button.edit-map:hover {
        background-color: var(--bg-primary);
        color: var(--accent-color);
    }

    .action-button.remove-map {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
        padding: 0.375rem;
    }

    .action-button.remove-map:hover {
        background-color: var(--danger-color);
        color: white;
        box-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 1rem;
        color: var(--text-secondary);
        gap: 0.75rem;
        text-align: center;
    }

    .empty-state .material-icons {
        font-size: 3rem;
        opacity: 0.6;
        color: var(--text-secondary);
    }

    .empty-state p {
        margin: 0;
        font-size: 1rem;
    }

    .empty-subtitle {
        font-size: 0.875rem !important;
        opacity: 0.8;
    }

    .maps-list {
        display: flex;
        flex-direction: column;
        gap: 1rem;
        /* max-height: 60vh;
        overflow-y: auto; */
    }

    .map-card {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        transition: all 0.2s ease;
        cursor: pointer;
    }

    .map-card:hover {
        background-color: var(--bg-primary);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    .map-card:focus {
        outline: 2px solid var(--accent-color);
        outline-offset: 2px;
    }

    .map-index {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 2rem;
        height: 2rem;
        background-color: var(--accent-color);
        color: white;
        border-radius: 50%;
        font-weight: 600;
        font-size: 0.875rem;
        flex-shrink: 0;
    }

    .map-cover {
        width: 3rem;
        height: 3rem;
        border-radius: 0.375rem;
        overflow: hidden;
        flex-shrink: 0;
    }

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

    .map-info {
        flex: 1;
        min-width: 0;
    }

    .map-title {
        font-size: 1rem;
        font-weight: 500;
        margin: 0 0 0.25rem 0;
        color: var(--text-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .map-artist {
        color: var(--text-secondary);
        font-size: 0.875rem;
        margin: 0 0 0.5rem 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .map-details {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        flex-wrap: wrap;
    }

    .difficulty-badge {
        padding: 0.125rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    .difficulty-0 { background-color: #10B981; color: white; } /* Easy - Green */
    .difficulty-1 { background-color: #3B82F6; color: white; } /* Normal - Blue */
    .difficulty-2 { background-color: #F59E0B; color: white; } /* Hard - Yellow */
    .difficulty-3 { background-color: #EF4444; color: white; } /* Expert - Red */
    .difficulty-4 { background-color: #8B5CF6; color: white; } /* Expert+ - Purple */

    .modifiers {
        display: flex;
        gap: 0.25rem;
        flex-wrap: wrap;
    }

    .modifier-tag {
        padding: 0.125rem 0.375rem;
        background-color: rgba(79, 70, 229, 0.1);
        color: var(--accent-color);
        border-radius: 0.25rem;
        font-size: 0.625rem;
        font-weight: 500;
        border: 1px solid rgba(79, 70, 229, 0.2);
    }

    .map-actions {
        display: flex;
        gap: 0.5rem;
        flex-shrink: 0;
    }

    /* Dialog Styles */
    .dialog-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        backdrop-filter: blur(4px);
    }

    .dialog {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        max-width: 500px;
        width: 90%;
        max-height: 80vh;
        overflow: hidden;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        border: 1px solid var(--bg-tertiary);
    }

    .dialog-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.5rem 1.5rem 0 1.5rem;
    }

    .dialog-header h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin: 0;
        color: var(--text-primary);
    }

    .dialog-close {
        background: none;
        border: none;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 0.25rem;
        border-radius: 0.25rem;
        transition: all 0.2s ease;
    }

    .dialog-close:hover {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }

    .dialog-content {
        padding: 1.5rem;
    }

    .dialog-content p {
        color: var(--text-primary);
        margin: 0 0 1.5rem 0;
        font-size: 1rem;
        line-height: 1.5;
    }

    .map-preview {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
    }

    .preview-cover {
        width: 3rem;
        height: 3rem;
        border-radius: 0.375rem;
        object-fit: cover;
        flex-shrink: 0;
    }

    .preview-info {
        flex: 1;
        min-width: 0;
    }

    .preview-info h4 {
        font-size: 1rem;
        font-weight: 500;
        margin: 0 0 0.25rem 0;
        color: var(--text-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .preview-info p {
        color: var(--text-secondary);
        font-size: 0.875rem;
        margin: 0 0 0.5rem 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .dialog-actions {
        display: flex;
        gap: 0.75rem;
        padding: 0 1.5rem 1.5rem 1.5rem;
        justify-content: flex-end;
    }

    .cancel-button {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }

    .cancel-button:hover {
        background-color: var(--bg-primary);
    }

    .confirm-button {
        background-color: var(--accent-color);
        color: white;
    }

    .confirm-button:hover {
        background-color: var(--accent-hover);
        box-shadow: 0 0 10px var(--accent-glow);
    }

    .material-icons {
        font-family: 'Material Icons';
        font-weight: normal;
        font-style: normal;
        font-size: 20px;
        line-height: 1;
        letter-spacing: normal;
        text-transform: none;
        display: inline-block;
        white-space: nowrap;
        word-wrap: normal;
        direction: ltr;
        -webkit-font-feature-settings: 'liga';
        -webkit-font-smoothing: antialiased;
    }

    /* Scrollbar Styling
    .maps-list::-webkit-scrollbar {
        width: 0.375rem;
    }

    .maps-list::-webkit-scrollbar-track {
        background: var(--bg-primary);
        border-radius: 0.375rem;
    }

    .maps-list::-webkit-scrollbar-thumb {
        background: var(--bg-tertiary);
        border-radius: 0.375rem;
    }

    .maps-list::-webkit-scrollbar-thumb:hover {
        background: var(--text-secondary);
    } */

    /* Responsive Design */
    @media (max-width: 768px) {
        .queue-header {
            flex-direction: column;
            gap: 1rem;
            align-items: stretch;
        }

        .map-card {
            flex-direction: column;
            text-align: center;
            gap: 0.75rem;
        }

        .map-info {
            text-align: center;
        }

        .map-title,
        .map-artist {
            white-space: normal;
            overflow: visible;
            text-overflow: unset;
        }

        .map-details {
            justify-content: center;
        }

        .dialog {
            width: 95%;
            margin: 1rem;
        }

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

        .preview-info h4,
        .preview-info p {
            white-space: normal;
            overflow: visible;
            text-overflow: unset;
        }

        .dialog-actions {
            flex-direction: column-reverse;
        }
    }
</style>