<script lang="ts">
    import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, discordDataStore, client, TAServerAPIPort } from "$lib/stores";
    import { onMount, onDestroy } from "svelte";
    //@ts-ignore
    import { Match, Tournament, TAClient, Response_ResponseType, Map } from 'moons-ta-client';
    import SideMenu from "$lib/components/menus/SideMenuTournaments.svelte";
    import InfoPopup from "$lib/components/notifications/InfoPopup.svelte";
    import { bufferToImageUrl } from "$lib/services/taImages.js";
    import { generateRandomHexColor } from "$lib/services/colours.js";
    import { v4 as uuidv4 } from "uuid";
    import Popup from "$lib/components/notifications/Popup.svelte";
    import MapPoolModal from "$lib/components/popups/AddNewMapPool.svelte";
    import { goto } from "$app/navigation";

    export let data;

    const tournamentGuid: string = data.tournamentGuid;
    let tournament: Tournament | undefined;
    let isLoading = false;
    let error: string | null = null;
    
    // MapPool data
    interface MapPool {
        guid: string;
        name: string;
        image: string;
        color?: string;
    }

    interface TAMapPool {
        guid: string;
        name: string;
        image: Uint8Array;
        maps: Map[];
    }
    
    let mapPools: MapPool[] = [];
    
    // Map pool modal state
    let showMapPoolModal: boolean = false;
    
    // Info popup state
    let showInfoPopup: boolean = false;
    let infoPopupContent: string = "";

    let showSuccessfullySaved = false;
    
    // Delete confirmation popup
    let showDeleteConfirmation = false;
    let mapPoolToDelete: string | null = null;
    let mapPoolNameToDelete: string = "";
    
    // Remove 'Bearer ' from the token
    if ($authTokenStore) {
        const cleanToken = $authTokenStore.replace('Bearer ', '');
        client.setAuthToken(cleanToken);
    }
    
    function openInfoPopup(content: string) {
        infoPopupContent = content;
        showInfoPopup = true;
    }
    
    function closeInfoPopup() {
        showInfoPopup = false;
    }
    
    function openMapPoolModal() {
        showMapPoolModal = true;
    }
    
    function closeMapPoolModal() {
        showMapPoolModal = false;
    }

    function closeNotification() {
        showSuccessfullySaved = false;
    }
    
    function openDeleteConfirmation(poolGuid: string, poolName: string) {
        mapPoolToDelete = poolGuid;
        mapPoolNameToDelete = poolName;
        showDeleteConfirmation = true;
    }
    
    function closeDeleteConfirmation() {
        showDeleteConfirmation = false;
        mapPoolToDelete = null;
        mapPoolNameToDelete = "";
    }
    
    async function handleMapPoolCreated(event: CustomEvent<TAMapPool>) {
        const newMapPool = event.detail;
        let createMapPoolResponse = await client.addTournamentPool(tournamentGuid, newMapPool.name, newMapPool.image, []);
        
        if(createMapPoolResponse.type !== Response_ResponseType.Success) {
            error = "Failed to create the new map pool! Please refresh this page!";
        } else {
            let mapPoolImage;
            try {
                mapPoolImage = bufferToImageUrl(newMapPool.image);
            } catch (error) {
                mapPoolImage = "/talogo.png"
            }
            
            mapPools = [...mapPools, {
                name: newMapPool.name,
                image: mapPoolImage,
                guid: newMapPool.guid,
                color: generateRandomHexColor()
            }];
            
            showSuccessfullySaved = true;
        }
    }
    
    async function editMapPool(poolGuid: string) {
        goto(`/tournaments/${tournamentGuid}/mappools/${poolGuid}`);
    }
    
    async function deleteMapPool() {
        if (!mapPoolToDelete) return;
        
        let removeMapPoolResponse = await client.removeTournamentPool(tournamentGuid, mapPoolToDelete);

        if(removeMapPoolResponse.type !== Response_ResponseType.Success) {
            error = "Failed to remove map pool! Please refresh this page!";
        } else {
            mapPools = mapPools.filter(pool => pool.guid !== mapPoolToDelete);
        }
        
        closeDeleteConfirmation();
    }

    async function fetchMapPoolsData() {
        if (!$authTokenStore) {
            window.location.href = '/discordAuth';
            return;
        }
        
        isLoading = true;
        error = null;
        
        try {
            if(!client.isConnected) {
                const connectResult = await client.connect($TAServerUrl, $TAServerPort);

                if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
                    throw new Error(connectResult.details.connect.message);
                }
            }
            
            if(!client.stateManager.getTournament(tournamentGuid)!.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
                const joinResult = await client.joinTournament(tournamentGuid);
                if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
                    throw new Error('Could not join tournament');
                }
            }            

            tournament = client.stateManager.getTournament(tournamentGuid)!;

            if(tournament?.settings?.enablePools == false) {
                error = "The map pools feature is not enabled for this tournament. Please enable it in the Settings section.";
                return;
            }
            
            // Get map pools from tournament data
            tournament?.settings?.pools.map(async (pool) => {
                mapPools = [...mapPools, {
                    name: pool.name,
                    image: pool.image && pool.image.length > 2 ? `https://${$TAServerUrl}:${$TAServerAPIPort}/api/file/${pool.image}` : '/talogo.png',
                    guid: pool.guid,
                    color: generateRandomHexColor()
                }];
            });
            
        } catch (err) {
            console.error('Error fetching map pools data:', err);
            error = err instanceof Error ? err.message : 'An unknown error occurred';
        } finally {
            isLoading = false;
        }
    }

    onMount(async() => {
        if ($authTokenStore) {
            await fetchMapPoolsData();
        } else {
            window.location.href = "/discordAuth"
        }
    });
</script>

<div class="layout">
    <main class="dashboard">
        <SideMenu currentPage="mappools" tournamentName={tournament?.settings?.tournamentName} tournamnentGuid={tournamentGuid} />
        
        <div class="content-area">
            <div class="content-header">
                <h2>Map Pools Management</h2>
                <div class="actions">
                    {#if !error && !isLoading}
                        <button class="action-button add" on:click={openMapPoolModal}>
                            <span class="material-icons">add</span>
                            Create Map Pool
                        </button>
                        <button class="action-button refresh" on:click={fetchMapPoolsData}>
                            <span class="material-icons">refresh</span>
                            Refresh
                        </button>
                    {/if}
                </div>
            </div>
            
            <div class="mappools-header">
                <h3>Map Pools</h3>
                <button class="info-button" on:click={() => openInfoPopup("Map pools allow you to organize maps into groups for different stages of your tournament. Each map pool can contain multiple maps with their own settings.")}>
                    <span class="material-icons">info</span>
                </button>
            </div>
            
            {#if isLoading}
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Loading map pools data...</p>
                </div>
            {:else if error}
                <div class="error-container">
                    <span class="material-icons">error_outline</span>
                    <p>{error}</p>
                    <button class="retry-button" on:click={fetchMapPoolsData}>Retry</button>
                </div>
            {:else if mapPools.length === 0}
                <div class="no-mappools">
                    <span class="material-icons">map</span>
                    <p>No map pools have been created yet</p>
                    <button class="action-button add" on:click={openMapPoolModal}>
                        <span class="material-icons">add</span>
                        Create First Map Pool
                    </button>
                </div>
            {:else}
                <div class="mappools-grid">
                    {#each mapPools as pool}
                        <div class="mappool-card" style="border-left: 4px solid {pool.color}">
                            <div class="mappool-header">
                                <div class="mappool-info">
                                    <img 
                                        class="mappool-logo" 
                                        src={pool.image} 
                                        alt="{pool.name} logo"
                                    />
                                    <div>
                                        <h4>{pool.name}</h4>
                                    </div>
                                </div>
                                <div class="mappool-actions">
                                    <button 
                                        class="mappool-action edit" 
                                        title="Edit map pool" 
                                        on:click={() => editMapPool(pool.guid)}
                                    >
                                        <span class="material-icons">edit</span>
                                    </button>
                                    <button 
                                        class="mappool-action delete" 
                                        title="Delete map pool" 
                                        on:click={() => openDeleteConfirmation(pool.guid, pool.name)}
                                    >
                                        <span class="material-icons">delete</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    {/each}
                </div>
            {/if}
        </div>
    </main>
</div>

<!-- Map Pool Modal Component -->
{#if showMapPoolModal}
    <MapPoolModal 
        on:close={closeMapPoolModal} 
        on:mapPoolCreated={handleMapPoolCreated}
    />
{/if}

<!-- Info Popup -->
{#if showInfoPopup}
    <InfoPopup content={infoPopupContent} onClose={closeInfoPopup} />
{/if}

<!-- Delete Confirmation Popup -->
{#if showDeleteConfirmation}
    <div class="popup-overlay">
        <div class="popup-container delete-confirmation">
            <div class="popup-header">
                <h3>Delete Map Pool</h3>
                <button class="close-button" on:click={closeDeleteConfirmation}>
                    <span class="material-icons">close</span>
                </button>
            </div>
            
            <div class="popup-content">
                <p>Are you sure you want to delete the map pool <strong>{mapPoolNameToDelete}</strong>?</p>
                <p class="warning">This action cannot be undone!</p>
                
                <div class="popup-actions">
                    <button class="action-button cancel" on:click={closeDeleteConfirmation}>Cancel</button>
                    <button class="action-button delete" on:click={deleteMapPool}>
                        Delete Map Pool
                    </button>
                </div>
            </div>
        </div>
    </div>
{/if}

<Popup
    bind:open={showSuccessfullySaved}
    message="Successfully created a new map pool!"
    icon="check"
    iconColor="success"
    buttons={[]}
    on:close={closeNotification}
/>

<style>
    /* Main layout */
    .layout {
        display: flex;
        height: 100vh;
        overflow: hidden;
    }
    
    .dashboard {
        display: flex;
        flex: 1;
        overflow: hidden;
    }
    
    .content-area {
        flex: 1;
        padding: 2rem;
        overflow-y: auto;
    }
    
    /* Content header */
    .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    
    .content-header h2 {
        font-size: 1.5rem;
        font-weight: 600;
        margin: 0;
    }
    
    .actions {
        display: flex;
        gap: 0.75rem;
    }
    
    .action-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        background-color: var(--bg-secondary);
        border: none;
        border-radius: 0.375rem;
        color: var(--text-primary);
        font-weight: 500;
        padding: 0.5rem 1rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    
    .action-button.add, 
    .action-button.create {
        background-color: var(--accent-color);
        color: white;
    }
    
    .action-button.add:hover, 
    .action-button.create:hover {
        background-color: var(--accent-hover);
    }
    
    .action-button.cancel {
        background-color: var(--bg-secondary);
    }
    
    .action-button.cancel:hover {
        background-color: var(--bg-tertiary);
    }
    
    .action-button.delete {
        background-color: #ff5555;
        color: white;
    }
    
    .action-button.delete:hover {
        background-color: #ff3333;
    }
    
    .action-button.refresh:hover {
        background-color: var(--bg-tertiary);
    }
    
    .action-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    /* Map Pools header with info button */
    .mappools-header {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .mappools-header h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin: 0;
    }
    
    .info-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--accent-color);
        padding: 0;
    }
    
    .info-button .material-icons {
        font-size: 1.125rem;
    }
    
    .info-button:hover {
        color: var(--accent-hover);
    }
    
    /* Map Pools grid */
    .mappools-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 1.5rem;
    }
    
    .mappool-card {
        background-color: var(--bg-secondary);
        border-radius: 0.5rem;
        padding: 1.25rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .mappool-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }
    
    .mappool-info {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .mappool-logo {
        width: 3rem;
        height: 3rem;
        border-radius: 0.375rem;
        object-fit: cover;
        background-color: var(--bg-tertiary);
    }
    
    .mappool-info h4 {
        margin: 0;
        font-size: 1.125rem;
        font-weight: 500;
    }
    
    .mappool-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .mappool-action {
        background: none;
        border: none;
        width: 2rem;
        height: 2rem;
        border-radius: 0.25rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: var(--text-secondary);
    }
    
    .mappool-action:hover {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }
    
    .mappool-action.edit:hover {
        color: var(--accent-color);
    }
    
    .mappool-action.delete:hover {
        color: #ff5555;
    }
    
    /* No map pools state */
    .no-mappools {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        padding: 3rem 2rem;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
    }
    
    .no-mappools .material-icons {
        font-size: 3rem;
        color: var(--text-secondary);
        margin-bottom: 1rem;
    }
    
    .no-mappools p {
        color: var(--text-secondary);
        margin-bottom: 1.5rem;
    }
    
    /* Loading state */
    .loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 0;
    }
    
    .spinner {
        width: 3rem;
        height: 3rem;
        border: 0.25rem solid rgba(var(--accent-color-rgb), 0.2);
        border-radius: 50%;
        border-top-color: var(--accent-color);
        animation: spin 1s linear infinite;
        margin-bottom: 1rem;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* Error state */
    .error-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 0;
        text-align: center;
    }
    
    .error-container .material-icons {
        font-size: 3rem;
        color: #ff5555;
        margin-bottom: 1rem;
    }
    
    .retry-button {
        background-color: var(--accent-color);
        border: none;
        border-radius: 0.375rem;
        color: white;
        font-weight: 500;
        padding: 0.5rem 1rem;
        margin-top: 1rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    
    .retry-button:hover {
        background-color: var(--accent-hover);
    }
    
    /* Delete confirmation popup */
    .popup-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;
    }
    
    .popup-container {
        background-color: var(--bg-primary);
        border-radius: 0.75rem;
        width: 90%;
        max-width: 500px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    }
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--bg-secondary);
    }
    
    .popup-header h3 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
    }
    
    .close-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        width: 2rem;
        height: 2rem;
        border-radius: 0.25rem;
    }
    
    .close-button:hover {
        background-color: var(--bg-secondary);
        color: var(--text-primary);
    }
    
    .popup-content {
        padding: 1.5rem;
    }
    
    .popup-content p {
        margin-top: 0;
    }
    
    .popup-content .warning {
        color: #ff5555;
        font-weight: 500;
    }
    
    .popup-actions {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        margin-top: 1.5rem;
    }
    
    /* Responsive design */
    @media (max-width: 768px) {
        .mappools-grid {
            grid-template-columns: 1fr;
        }
        
        .content-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem;
        }
        
        .actions {
            width: 100%;
        }
        
        .action-button {
            flex: 1;
            justify-content: center;
        }
    }
</style>