<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 } from 'moons-ta-client';
    import SideMenu from "$lib/components/menus/SideMenuTournaments.svelte";
    import InfoPopup from "$lib/components/notifications/InfoPopup.svelte";
    import { bufferToImageUrl, convertImageToUint8Array, linkToUint8Array } 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";

    export let data;

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

    interface TATeam {
        guid: string;
        name: string;
        image: Uint8Array;
    }
    
    let teams: Team[] = [];
    
    // New team popup state
    let showTeamPopup: boolean = false;
    let newTeamName: string = "";
    let newTeamDescription: string = "";
    let newTeamColor: string = "#3366ff"; // Default color
    let teamImageBuffer: Uint8Array | null = null;
    let teamImagePreview: string | null = null;
    
    // Info popup state
    let showInfoPopup: boolean = false;
    let infoPopupContent: string = "";

    let showSuccessfullySaved = false;
    
    // File upload
    let fileInput: HTMLInputElement;

    // 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 openTeamPopup() {
        // Reset form fields
        newTeamName = "";
        newTeamDescription = "";
        newTeamColor = "#3366ff";
        teamImageBuffer = null;
        teamImagePreview = null;
        
        showTeamPopup = true;
    }
    
    function closeTeamPopup() {
        showTeamPopup = false;
    }
    
    function handleImageUpload() {
        fileInput.click();
    }

    function closeNotification() {
        showSuccessfullySaved = false;
    }
    
    function onFileSelected(event: Event) {
        const target = event.target as HTMLInputElement;
        const files = target.files;
        
        if (files && files.length > 0) {
            const file = files[0];
            const reader = new FileReader();
            
            reader.onload = (e) => {
                const result = e.target?.result;
                if (result instanceof ArrayBuffer) {
                    teamImageBuffer = new Uint8Array(result);
                    // Create preview URL
                    const blob = new Blob([result as ArrayBuffer], { type: file.type });
                    teamImagePreview = URL.createObjectURL(blob);
                }
            };
            
            reader.readAsArrayBuffer(file);
        }
    }
    
    async function createTeam() {
        // Add team to the list
        const newTeam: TATeam = {
            guid: uuidv4(),
            name: newTeamName,
            image: teamImageBuffer || new Uint8Array(1)
        };

        console.log(newTeam);
        
        let createTeamResponse = await client.addTournamentTeam(tournamentGuid, newTeam.name, newTeam.image);
        if(createTeamResponse.type !== Response_ResponseType.Success) {
            error = "Failed to create the new team! Please refresh this page!";
        } else {
            let teamImage;
            try {
                teamImage = bufferToImageUrl(teamImageBuffer || new Uint8Array(1));
            } catch (error) {
                teamImage = "/talogo.png"
            }
            await teams.push({
                name: newTeam.name,
                image: teamImage,
                guid: newTeam.guid,
                color: generateRandomHexColor()
            });
        }

        // Close the popup
        closeTeamPopup();
    }
    
    async function deleteTeam(teamGuid: string) {
        let removeTeamResponse = await client.removeTournamentTeam(tournamentGuid, teamGuid);

        if(removeTeamResponse.type !== Response_ResponseType.Success) {
            error = "Failed to remove team! Please refresh this page!";
        } else {
            // Remove team from the list
            teams = teams.filter(team => team.guid !== teamGuid);
        }        
    }

    async function fetchTeamsData() {
        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?.enableTeams == false) {
                error = "The teams feature is not enabled for this tournament. Please enable it in the Settings section.";
                return;
            }
            console.log(tournament)
            
            // For demo purposes, we'll create some sample teams
            // In a real app, this would come from the tournament data
            tournament?.settings?.teams.map(async (team) => {
                await teams.push({
                    name: team.name,
                    image: team.image && team.image.length > 2 ? `https://${$TAServerUrl}:${$TAServerAPIPort}/api/file/${team.image}` : '/talogo.png',
                    guid: team.guid,
                    color: generateRandomHexColor()
                });
            });
            
        } catch (err) {
            console.error('Error fetching teams data:', err);
            error = err instanceof Error ? err.message : 'An unknown error occurred';
        } finally {
            isLoading = false;
        }
    }

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

<div class="layout">
    <main class="dashboard">
        <SideMenu currentPage="teams" tournamentName={tournament?.settings?.tournamentName} tournamnentGuid={tournamentGuid} />
        
        <div class="content-area">
            <div class="content-header">
                <h2>Teams Management</h2>
                <div class="actions">
                    {#if !error && !isLoading}
                        <button class="action-button add" on:click={openTeamPopup}>
                            <span class="material-icons">add</span>
                            Create Team
                        </button>
                        <button class="action-button refresh" on:click={fetchTeamsData}>
                            <span class="material-icons">refresh</span>
                            Refresh
                        </button>
                    {/if}
                </div>
            </div>
            
            <div class="teams-header">
                <h3>Teams</h3>
                <button class="info-button" on:click={() => openInfoPopup("Teams allow players to be organized into groups during the tournament. Each team can have its own name, description, color, and logo.")}>
                    <span class="material-icons">info</span>
                </button>
            </div>
            
            {#if isLoading}
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Loading teams 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={fetchTeamsData}>Retry</button>
                </div>
            {:else if teams.length === 0}
                <div class="no-teams">
                    <span class="material-icons">groups</span>
                    <p>No teams have been created yet</p>
                    <button class="action-button add" on:click={openTeamPopup}>
                        <span class="material-icons">add</span>
                        Create First Team
                    </button>
                </div>
            {:else}
                <div class="teams-grid">
                    {#each teams as team}
                        <div class="team-card" style="border-left: 4px solid {team.color}">
                            <div class="team-header">
                                <div class="team-info">
                                    <img 
                                        class="team-logo" 
                                        src={team.image} 
                                        alt="{team.name} logo"
                                    />
                                    <div>
                                        <h4>{team.name}</h4>
                                    </div>
                                </div>
                                <div class="team-actions">
                                    <button 
                                        class="team-action delete" 
                                        title="Delete team" 
                                        on:click={() => deleteTeam(team.guid)}
                                    >
                                        <span class="material-icons">delete</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    {/each}
                </div>
            {/if}
        </div>
    </main>
</div>

<!-- Create Team Popup -->
{#if showTeamPopup}
    <div class="popup-overlay">
        <div class="popup-container">
            <div class="popup-header">
                <h3>Create New Team</h3>
                <button class="close-button" on:click={closeTeamPopup}>
                    <span class="material-icons">close</span>
                </button>
            </div>
            
            <div class="popup-content">
                <div class="form-group">
                    <label for="team-name">Team Name</label>
                    <input 
                        type="text" 
                        id="team-name" 
                        class="form-input" 
                        bind:value={newTeamName} 
                        placeholder="Enter team name"
                        required
                    />
                </div>
                
                <div class="form-group">
                    <!-- svelte-ignore a11y-label-has-associated-control -->
                    <label>Team Logo (Optional)</label>
                    <div class="image-upload-container">
                        <div class="image-preview">
                            {#if teamImagePreview}
                                <img src={teamImagePreview} alt="Team logo preview" />
                            <!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
                            <!-- svelte-ignore a11y-no-static-element-interactions -->
                            {:else}
                                <!-- svelte-ignore a11y-click-events-have-key-events -->
                                <!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
                                <img on:click={handleImageUpload} src="/talogo.png" alt="Default logo" />
                                <!-- svelte-ignore a11y-no-static-element-interactions -->
                                <!-- svelte-ignore a11y-click-events-have-key-events -->
                                <div on:click={handleImageUpload} class="upload-overlay">
                                    <span class="material-icons">add_photo_alternate</span>
                                </div>
                            {/if}
                        </div>
                        <button class="action-button upload" on:click={handleImageUpload}>
                            <span class="material-icons">upload</span>
                            {teamImagePreview ? 'Change Logo' : 'Upload Logo'}
                        </button>
                        <input 
                            type="file" 
                            accept="image/*" 
                            style="display: none" 
                            bind:this={fileInput} 
                            on:change={onFileSelected}
                        />
                    </div>
                </div>
                
                <div class="popup-actions">
                    <button class="action-button cancel" on:click={closeTeamPopup}>Cancel</button>
                    <button 
                        class="action-button create" 
                        on:click={createTeam}
                        disabled={!newTeamName}
                    >
                        Create Team
                    </button>
                </div>
            </div>
        </div>
    </div>
{/if}

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

<Popup
    bind:open={showSuccessfullySaved}
    message="Successfully saved the tournament information!"
    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.refresh:hover {
        background-color: var(--bg-tertiary);
    }
    
    .action-button.upload {
        background-color: var(--accent-color);
        color: white;
    }
    
    .action-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    /* Teams header with info button */
    .teams-header {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 1rem;
    }
    
    .teams-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);
    }
    
    /* Teams grid */
    .teams-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 1.5rem;
    }
    
    .team-card {
        background-color: var(--bg-secondary);
        border-radius: 0.5rem;
        padding: 1.25rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .team-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }
    
    .team-info {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .team-logo {
        width: 3rem;
        height: 3rem;
        border-radius: 0.375rem;
        object-fit: cover;
        background-color: var(--bg-tertiary);
    }
    
    .team-info h4 {
        margin: 0;
        font-size: 1.125rem;
        font-weight: 500;
    }
    
    .team-description {
        margin: 0.25rem 0 0;
        font-size: 0.875rem;
        color: var(--text-secondary);
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
    }
    
    .team-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .team-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);
    }
    
    .team-action:hover {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }
    
    .team-action.delete:hover {
        color: #ff5555;
    }
    
    /* No teams state */
    .no-teams {
        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-teams .material-icons {
        font-size: 3rem;
        color: var(--text-secondary);
        margin-bottom: 1rem;
    }
    
    .no-teams 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);
    }
    
    /* Create Team 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;
    }
    
    .form-group {
        margin-bottom: 1.25rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
        font-size: 0.9375rem;
    }
    
    .form-input {
        width: 100%;
        padding: 0.625rem 0.75rem;
        background-color: var(--bg-tertiary);
        border: none;
        border-radius: 0.375rem;
        color: var(--text-primary);
        font-size: 0.9375rem;
        font-family: inherit;
    }
    
    .form-input:focus {
        outline: 2px solid var(--accent-color);
    }
    
    /* Color picker */
    .color-picker-container {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .color-picker {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        width: 3rem;
        height: 3rem;
        border: none;
        border-radius: 0.375rem;
        background-color: transparent;
        cursor: pointer;
    }
    
    .color-picker::-webkit-color-swatch-wrapper {
        padding: 0;
    }
    
    .color-picker::-webkit-color-swatch {
        border: none;
        border-radius: 0.375rem;
    }
    
    .color-value {
        font-family: monospace;
        font-size: 0.9375rem;
        color: var(--text-secondary);
    }
    
    /* Image upload in popup */
    .image-upload-container {
        display: flex;
        flex-direction: column;
        gap: 1rem;
        align-items: flex-start;
    }
    
    .image-preview {
        width: 6rem;
        height: 6rem;
        border-radius: 0.375rem;
        overflow: hidden;
        background-color: var(--bg-tertiary);
        position: relative;
    }
    
    .image-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .upload-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.2);
        color: white;
    }
    
    .popup-actions {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        margin-top: 1.5rem;
    }
    
    /* Responsive design */
    @media (max-width: 768px) {
        .teams-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>