<script lang="ts">
    import { TABotTokenStore, TAServerPort, TAServerUrl, authTokenStore, client } from "$lib/stores";
    import { onMount, onDestroy } from "svelte";
    import { bkAPIUrl } from '$lib/config.json';
    //@ts-ignore
    import { Match, Tournament, TAClient, Response_ResponseType, User, User_PlayStates, User_ClientTypes } from 'moons-ta-client';
    import { writable } from "svelte/store";
    import SideMenu from "$lib/components/menus/SideMenuTournaments.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;
    let matches: Match[] = [];
    let availablePlayers: User[] = [];
    
    // Store for selected player guids
    const selectedPlayerGuids = writable<string[]>([]);

    // Remove 'Bearer ' from the token
    if($authTokenStore) {
        const cleanToken = $authTokenStore.replace('Bearer ', '');
        client.setAuthToken(cleanToken);
    }

    // Handle player selection
    function togglePlayerSelection(player: any) {
        $selectedPlayerGuids = $selectedPlayerGuids.includes(player.guid)
            ? $selectedPlayerGuids.filter(guid => guid !== player.guid)
            : [...$selectedPlayerGuids, player.guid];
    }
    
    // Return status color based on player status
    function getStatusColor(status: User_PlayStates): string {
        switch (status) {
            case User_PlayStates.InGame:
                return "var(--danger-color)";
            case User_PlayStates.InMenu:
                return "#FCD34D"; // Yellow
            case User_PlayStates.WaitingForCoordinator:
                return "#10B981"; // Green
            default:
                return "var(--text-secondary)";
        }
    }
    
    // Handle match status changes
    function handleMatchUpdated(params: any) {
        console.log("matchUpdate", params);
        if (params[1].guid === tournamentGuid) {
            // Update matches list
            fetchTournamentData();
        }
    };
    
    // Handle match deletion
    function handleMatchDeleted(matchInfo: any) {
        console.log('matchDeleted', matchInfo)
        if (matchInfo[1].guid === tournamentGuid) {
            // Update matches list
            fetchTournamentData();
        }
    };

    // Handle match deletion
    function handleMatchCreated(matchInfo: any) {
        console.log('matchCreated', matchInfo);
        if (matchInfo[1].guid === tournamentGuid) {
            // Update matches list
            fetchTournamentData();
        }
    };

    async function fetchTournamentData() {
        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);
                }
            }

            tournament = client.stateManager.getTournament(tournamentGuid);
            if(!tournament?.users.some(user => user.guid == client.stateManager.getSelfGuid())) {
                const joinResult = await client.joinTournament(tournamentGuid);
                console.log('jointournament', joinResult);
                if (joinResult.details.oneofKind !== 'join' || joinResult.type === Response_ResponseType.Fail) {
                    throw new Error('Could not join tournament');
                }

                tournament = joinResult.details.join.state?.tournaments.find((x: Tournament) => x.guid === tournamentGuid);
            }

            // Wait for state to be fully initialized
            await new Promise(resolve => setTimeout(resolve, 1000));

            // Get all matches for this tournament
            matches = client.stateManager.getMatches(tournamentGuid) || [];
            
            // Get all users for this tournament
            const allUsers = tournament!.users.filter(x => x.clientType === 0) || [];
            
            // Get users not in matches
            let allUsersGuidArray = allUsers.map(user => user.guid);
            const usersInMatches = new Set();
            matches.forEach(match => {
                match.associatedUsers.forEach(async(userGuid) => {
                    if(allUsersGuidArray.includes(userGuid)){
                        usersInMatches.add(userGuid);
                    }
                });
            });
            
            availablePlayers = allUsers.filter(user => !matches.some(match => match.associatedUsers.includes(user.guid)));
            
            client.on('createdMatch', (params) => {
                console.log("paramsUpdate", params);
            });
        } catch (err) {
            console.error('Error fetching tournament data:', err);
            error = err instanceof Error ? err.message : 'An unknown error occurred';
            matches = [];
            availablePlayers = [];
        } finally {
            isLoading = false;
        }
    }

    async function createMatch() {
        const response = await client.createMatch(tournament!.guid, {
            guid: '00000000-0000-4000-00000000',
            leader: client.stateManager.getSelfGuid(),
            associatedUsers: $selectedPlayerGuids
        });

        console.log("Match created! Response: ", response);

        const newMatch = (response as any).details.createMatch.match;

        goto(`/tournaments/${tournamentGuid}/matches/${newMatch.guid}`);
    }

    async function handleUserConnected(params: [User, Tournament]) {
        if(params[1].guid == tournament?.guid && params[0].clientType == User_ClientTypes.Player) {
            availablePlayers = [
                ...availablePlayers,
                params[0]
            ];
        }
    }

    async function handleUserDisconnected(params: [User, Tournament]) {
        if(params[1].guid == tournament?.guid) {
            if(availablePlayers.some(x => x.guid == params[0].guid)) {
                availablePlayers = availablePlayers.filter(x => x.guid !== params[0].guid);
            } else {
                let newMatchObject = matches.find(x => x.associatedUsers.includes(params[0].guid))!;
                newMatchObject.associatedUsers = newMatchObject.associatedUsers.filter(x => x !== params[0].guid);
                matches = [
                    ...matches.filter(x => x.guid !== newMatchObject.guid),
                    newMatchObject
                ]
            }
        }
    }

    function getDiscordNameBecauseShit(user: User) {
        return user.discordInfo?.username || "";
    }

    onMount(async() => {
        if ($authTokenStore) {
            await fetchTournamentData();
            client.stateManager.on('matchCreated', handleMatchCreated);
            client.stateManager.on('matchDeleted', handleMatchDeleted);
            client.stateManager.on('matchUpdated', handleMatchUpdated);
            client.stateManager.on('userConnected', handleUserConnected);
            client.stateManager.on('userDisconnected', handleUserDisconnected);
        } else {
            window.location.href = "/discordAuth"
        }
    });

    onDestroy(() => {
        client.stateManager.removeListener('matchUpdated', handleMatchUpdated);
        client.stateManager.removeListener('matchDeleted', handleMatchDeleted);
        client.stateManager.removeListener('matchCreated', handleMatchDeleted);
        client.stateManager.removeListener('userConnected', handleUserConnected);
        client.stateManager.removeListener('userDisconnected', handleUserDisconnected);
        client.removeListener('createdMatch', handleMatchUpdated)
        // client.disconnect();
    });
</script>

<div class="layout">
    <main class="dashboard">
        <SideMenu currentPage="matches" tournamentName={tournament?.settings?.tournamentName} tournamnentGuid={tournamentGuid} />
        
        <div class="content-area">
            <div class="content-header">
                <h2>Matches</h2>
                <div class="actions">
                    <button class="action-button refresh" on:click={fetchTournamentData}>
                        <span class="material-icons">refresh</span>
                    </button>
                </div>
            </div>
            
            {#if isLoading}
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Loading tournament 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={fetchTournamentData}>Retry</button>
                </div>
            {:else}
                <div class="dashboard-grid">
                    <div class="match-list">
                        <h3>Active Matches</h3>
                        {#if matches.length === 0}
                            <div class="empty-state">
                                <span class="material-icons">sports_esports</span>
                                <p>No active matches</p>
                            </div>
                        {:else}
                            <div class="match-cards">
                                {#each matches as match}
                                    <div class="match-card">
                                        <div class="match-header">
                                            <div class="match-status" style="background-color: {match.selectedMap ? 'var(--danger-color)' : '#FCD34D'}"></div>
                                            <h4>
                                                <img 
                                                    src={tournament?.users.find(x => x.guid == match.leader)?.discordInfo?.avatarUrl || "https://api.dicebear.com/7.x/identicon/svg?seed=" + tournament?.users.find(x => x.guid == match.leader)?.guid} 
                                                    alt="Player" 
                                                    class="player-avatar"
                                                />
                                                {tournament?.users.find(x => x.guid == match.leader)?.discordInfo?.username}'s Match
                                            </h4>
                                        </div>
                                        <div class="match-players">
                                            {#if match.associatedUsers && match.associatedUsers.length > 0}
                                                {#each match.associatedUsers as userGuid}
                                                    {#if client.stateManager.getUser(tournamentGuid, userGuid) && client.stateManager.getUser(tournamentGuid, userGuid)?.clientType == 0}
                                                        <div class="player-chip">
                                                            <img src={client.stateManager.getUser(tournamentGuid, userGuid)?.discordInfo?.avatarUrl || "https://api.dicebear.com/7.x/identicon/svg?seed=" + userGuid} 
                                                                alt="Player" 
                                                                class="player-avatar">
                                                            <span>{client.stateManager.getUser(tournamentGuid, userGuid)?.name || 'Unknown Player'}</span>
                                                        </div>
                                                    {/if}
                                                {/each}
                                            {:else}
                                                <p class="no-players">No players assigned</p>
                                            {/if}
                                        </div>
                                        <div class="match-actions">
                                            <a href={`/tournaments/${tournamentGuid}/matches/${match.guid}`} class="match-action-button">
                                                <span class="material-icons">visibility</span>
                                                View
                                            </a>
                                        </div>
                                    </div>
                                {/each}
                            </div>
                        {/if}
                    </div>
                    
                    <div class="player-list">
                        <h3>Available Players</h3>
                        <div class="search-container">
                            <span class="material-icons">search</span>
                            <input type="text" placeholder="Search players..." class="search-input">
                        </div>
                        {#if availablePlayers.length === 0}
                            <div class="empty-state">
                                <span class="material-icons">person_off</span>
                                <p>No available players</p>
                            </div>
                        {:else}
                            <div class="player-cards">
                                <!-- svelte-ignore a11y-click-events-have-key-events -->
                                {#each availablePlayers as player}
                                    {@const isSelected = $selectedPlayerGuids.includes(player.guid)}
                                    <!-- svelte-ignore a11y-no-static-element-interactions -->
                                    <div class="player-card {isSelected ? 'selected' : ''}" 
                                        on:click={() => togglePlayerSelection(player)}>
                                        <div class="player-status" style="background-color: {getStatusColor(player.playState)}"></div>
                                        <img src={player.discordInfo?.avatarUrl || "https://api.dicebear.com/7.x/identicon/svg?seed=" + player.guid} 
                                            alt="Player" 
                                            class="player-avatar">
                                        <div class="player-info">
                                            <h4>{player.name} ({getDiscordNameBecauseShit(player)})</h4>
                                            <p>{User_PlayStates[player.playState]}</p>
                                        </div>
                                    </div>
                                {/each}
                            </div>
                        {/if}
                    </div>
                </div>
                
                {#if $selectedPlayerGuids.length > 0}
                    <div class="selection-bar">
                        <p>{$selectedPlayerGuids.length} players selected</p>
                        <div class="selection-actions">
                            <button class="action-button create-match" on:click={createMatch}>
                                <span class="material-icons">add</span>
                                Create Match with Selection
                            </button>
                            <button class="action-button cancel" on:click={() => $selectedPlayerGuids = []}>
                                <span class="material-icons">close</span>
                                Clear Selection
                            </button>
                        </div>
                    </div>
                {/if}
            {/if}
        </div>
    </main>
</div>

<style>
    /* Global styles are inherited from the attached CSS */
    
    /* Dashboard layout */
    .dashboard {
        display: flex;
        height: calc(100vh - var(--navbar-height));
    }
    
    .content-area {
        flex: 1;
        padding: 1.5rem;
        overflow-y: auto;
    }
    
    .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    
    .content-header h2 {
        font-size: 1.75rem;
        font-weight: 600;
    }
    
    .actions {
        display: flex;
        gap: 0.75rem;
    }
    
    .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;
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }
    
    .action-button.create {
        background-color: var(--accent-color);
    }
    
    .action-button.create:hover {
        background-color: var(--accent-hover);
        box-shadow: 0 0 10px var(--accent-glow);
    }
    
    .action-button.refresh:hover {
        background-color: var(--bg-secondary);
    }
    
    /* Dashboard grid */
    .dashboard-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1.5rem;
    }
    
    /* Match list */
    .match-list, .player-list {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        padding: 1.5rem;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .match-list h3, .player-list h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin-bottom: 1rem;
    }
    
    .match-cards, .player-cards {
        display: flex;
        flex-direction: column;
        gap: 1rem;
        max-height: 60vh;
        overflow-y: auto;
    }
    
    /* Match card */
    .match-card {
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        padding: 1rem;
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .match-header {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }
    
    .match-status {
        width: 0.75rem;
        height: 0.75rem;
        border-radius: 50%;
        flex-shrink: 0;
    }
    
    .match-header h4 {
        font-weight: 500;
        font-size: 1rem;
    }
    
    .match-players {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
    }
    
    .player-chip {
        display: flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.25rem 0.5rem;
        background-color: var(--bg-primary);
        border-radius: 0.25rem;
        font-size: 0.875rem;
    }
    
    .player-avatar {
        width: 1.5rem;
        height: 1.5rem;
        border-radius: 50%;
        object-fit: cover;
    }
    
    .no-players {
        color: var(--text-secondary);
        font-size: 0.875rem;
        font-style: italic;
    }
    
    .match-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 0.5rem;
    }
    
    .match-action-button {
        display: flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.375rem 0.75rem;
        background-color: var(--accent-color);
        color: var(--text-primary);
        border-radius: 0.375rem;
        text-decoration: none;
        font-size: 0.875rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    
    .match-action-button:hover {
        background-color: var(--accent-hover);
        box-shadow: 0 0 10px var(--accent-glow);
    }
    
    /* Player list */
    .search-container {
        display: flex;
        align-items: center;
        background-color: var(--bg-tertiary);
        border-radius: 0.375rem;
        padding: 0.5rem 0.75rem;
        margin-bottom: 1rem;
    }
    
    .search-input {
        background: none;
        border: none;
        outline: none;
        color: var(--text-primary);
        font-size: 0.875rem;
        width: 100%;
        margin-left: 0.5rem;
    }
    
    /* Player card */
    .player-card {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 0.75rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        cursor: pointer;
        transition: all 0.2s ease;
        border: 2px solid transparent;
    }
    
    .player-card:hover {
        background-color: var(--bg-primary);
    }
    
    .player-card.selected {
        border-color: var(--danger-color);
        box-shadow: 0 0 10px rgba(239, 68, 68, 0.5);
    }
    
    .player-status {
        width: 0.75rem;
        height: 0.75rem;
        border-radius: 50%;
        flex-shrink: 0;
    }
    
    .player-card .player-avatar {
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        object-fit: cover;
    }
    
    .player-info {
        display: flex;
        flex-direction: column;
    }
    
    .player-info h4 {
        font-size: 0.9375rem;
        font-weight: 500;
    }
    
    .player-info p {
        font-size: 0.75rem;
        color: var(--text-secondary);
    }
    
    /* Empty state */
    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 2rem;
        color: var(--text-secondary);
        gap: 0.75rem;
    }
    
    .empty-state .material-icons {
        font-size: 2.5rem;
        opacity: 0.6;
    }
    
    /* Loading */
    .loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 50vh;
        gap: 1rem;
    }
    
    .spinner {
        width: 2.5rem;
        height: 2.5rem;
        border: 3px solid rgba(79, 70, 229, 0.2);
        border-radius: 50%;
        border-top-color: var(--accent-color);
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* Error container */
    .error-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 2rem;
        background-color: rgba(239, 68, 68, 0.1);
        border-radius: 0.75rem;
        color: var(--danger-color);
        gap: 0.75rem;
    }
    
    .error-container .material-icons {
        font-size: 2.5rem;
    }
    
    .retry-button {
        padding: 0.5rem 1rem;
        background-color: var(--danger-color);
        color: white;
        border: none;
        border-radius: 0.375rem;
        font-weight: 500;
        cursor: pointer;
        margin-top: 0.75rem;
    }
    
    .retry-button:hover {
        background-color: var(--danger-hover);
    }
    
    /* Selection bar */
    .selection-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: var(--bg-secondary);
        padding: 1rem 2rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
        z-index: 10;
    }
    
    .selection-actions {
        display: flex;
        gap: 0.75rem;
    }
    
    .action-button.create-match {
        background-color: var(--accent-color);
    }
    
    .action-button.create-match:hover {
        background-color: var(--accent-hover);
        box-shadow: 0 0 10px var(--accent-glow);
    }
    
    .action-button.cancel {
        background-color: var(--bg-tertiary);
    }
    
    .action-button.cancel:hover {
        background-color: var(--danger-color);
    }
    
    /* Material Icons */
    .material-icons {
        font-family: 'Material Icons';
        font-weight: normal;
        font-style: normal;
        font-size: 24px;
        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;
    }
</style>