<script lang="ts">
    import { createEventDispatcher } from "svelte";
    import { TAClient } from "moons-ta-client";
    
    const dispatch = createEventDispatcher();
    
    export let isOpen: boolean = false;
    export let taClient: TAClient;
    export let tournamentGuid: string;
    
    // User states
    let discordUserId: string = "";
    let isSearching: boolean = false;
    let userFound: boolean = false;
    let error: string | null = null;
    
    // Discord user data
    let discordUser: {
        discordId: string;
        discordUsername: string;
        discordAvatarUrl: string;
    } | null = null;
    
    // Permission settings
    let hasAdminPermission: boolean = false;
    let hasViewPermission: boolean = true;
    
    // This will be implemented by the parent component
    async function fetchDiscordUser() {
        // Placeholder function to be implemented externally
        isSearching = true;
        error = null;
        
        try {
            if(!taClient.isConnected) {
                throw new Error("TA Client is not connected. Please refresh site.")
            }
            if (discordUserId.length >= 17) {

                let user = await taClient.getDiscordInfo(tournamentGuid, discordUserId);
                console.log(user);
                discordUser = {
                    discordId: discordUserId,
                    discordUsername: (user as any).details.getDiscordInfo.discordUsername,
                    discordAvatarUrl: (user as any).details.getDiscordInfo.discordAvatarUrl
                };
                userFound = true;
            } else {
                throw new Error("Invalid Discord ID format");
            }
        } catch (err) {
            error = err instanceof Error ? err.message : "Failed to fetch user";
            userFound = false;
            discordUser = null;
        } finally {
            isSearching = false;
        }
    }
    
    function handleSearch() {
        if (discordUserId.trim() !== "") {
            fetchDiscordUser();
        }
    }
    
    function handleKeyDown(event: KeyboardEvent) {
        if (event.key === "Enter") {
            handleSearch();
        }
    }
    
    function resetForm() {
        discordUserId = "";
        discordUser = null;
        userFound = false;
        error = null;
        hasAdminPermission = false;
        hasViewPermission = true;
    }
    
    function closePopup() {
        resetForm();
        dispatch("close");
    }
    
    function addUser() {
        if (discordUser) {
            let permission;

            enum Permissions {
                "None" = 0,
                "View Only" = 1,
                "Administrator" = 2,
                "View and Administrator" = 3
            }

            if(hasAdminPermission && hasViewPermission) {
                permission = Permissions["View and Administrator"];
            } else if(hasViewPermission) {
                permission = Permissions["View Only"];
            } else if(hasAdminPermission) {
                permission = Permissions.Administrator;
            } else {
                permission = Permissions.None;
            }

            dispatch("addUser", {
                discordId: discordUser.discordId,
                discordUsername: discordUser.discordUsername,
                discordAvatarUrl: discordUser.discordAvatarUrl,
                permission
            });
            
            closePopup();
        }
    }
</script>

{#if isOpen}
<div class="popup-overlay">
    <div class="popup-container">
        <div class="popup-header">
            <h3>Add User</h3>
            <button class="close-button" on:click={closePopup}>
                <span class="material-icons">close</span>
            </button>
        </div>
        
        <div class="popup-content">
            <div class="search-section">
                <label for="discord-id">Discord User ID</label>
                <div class="search-input-container">
                    <input 
                        type="text" 
                        id="discord-id" 
                        bind:value={discordUserId} 
                        placeholder="Enter Discord User ID" 
                        on:keydown={handleKeyDown}
                        disabled={isSearching || userFound}
                    />
                    {#if !userFound}
                        <button 
                            class="search-button" 
                            on:click={handleSearch} 
                            disabled={isSearching || discordUserId.trim() === ""}
                        >
                            {#if isSearching}
                                <div class="spinner-small"></div>
                            {:else}
                                <span class="material-icons">search</span>
                            {/if}
                        </button>
                    {:else}
                        <button class="reset-button" on:click={resetForm}>
                            <span class="material-icons">refresh</span>
                        </button>
                    {/if}
                </div>
                
                {#if error}
                    <p class="error-message">{error}</p>
                {/if}
            </div>
            
            {#if userFound && discordUser}
                <div class="user-result">
                    <div class="user-preview">
                        <img 
                            src={discordUser.discordAvatarUrl} 
                            alt={discordUser.discordUsername} 
                            class="user-avatar"
                        />
                        <div class="user-info">
                            <h4>{discordUser.discordUsername}</h4>
                            <p class="user-id">ID: {discordUser.discordId}</p>
                        </div>
                    </div>
                    
                    <div class="permissions-section">
                        <h4>Permissions</h4>
                        
                        <div class="permission-option">
                            <div class="permission-label">
                                <label for="view-permission">View Permission</label>
                                <p class="permission-description">Can view tournament data (generally players)</p>
                            </div>
                            <label class="toggle">
                                <input type="checkbox" id="view-permission" bind:checked={hasViewPermission}>
                                <span class="slider"></span>
                            </label>
                        </div>
                        
                        <div class="permission-option">
                            <div class="permission-label">
                                <label for="admin-permission">Admin Permission</label>
                                <p class="permission-description">Can manage tournament settings (generally staff))</p>
                            </div>
                            <label class="toggle">
                                <input type="checkbox" id="admin-permission" bind:checked={hasAdminPermission}>
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                </div>
            {/if}
        </div>
        
        <div class="popup-actions">
            <button class="cancel-button" on:click={closePopup}>Cancel</button>
            <button 
                class="add-button" 
                on:click={addUser} 
                disabled={!userFound || (!hasViewPermission && !hasAdminPermission)}
            >
                Add User
            </button>
        </div>
    </div>
</div>
{/if}

<style>
    .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: 32rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        display: flex;
        flex-direction: column;
    }
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.5rem;
        border-bottom: 1px solid var(--bg-tertiary);
    }
    
    .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);
        padding: 0.5rem;
        border-radius: 0.375rem;
    }
    
    .close-button:hover {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }
    
    .popup-content {
        padding: 1.5rem;
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }
    
    .search-section {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .search-section label {
        font-weight: 500;
        font-size: 0.9375rem;
    }
    
    .search-input-container {
        display: flex;
        gap: 0.5rem;
    }
    
    .search-input-container input {
        flex: 1;
        background-color: var(--bg-tertiary);
        border: none;
        border-radius: 0.375rem;
        padding: 0.625rem 0.75rem;
        color: var(--text-primary);
        font-size: 0.9375rem;
    }
    
    .search-input-container input:focus {
        outline: 2px solid var(--accent-color);
    }
    
    .search-button, 
    .reset-button {
        background-color: var(--accent-color);
        border: none;
        border-radius: 0.375rem;
        width: 2.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        cursor: pointer;
    }
    
    .search-button:hover,
    .reset-button:hover {
        background-color: var(--accent-hover);
    }
    
    .search-button:disabled {
        background-color: var(--bg-tertiary);
        color: var(--text-secondary);
        cursor: not-allowed;
    }
    
    .error-message {
        color: #ff5555;
        font-size: 0.875rem;
        margin: 0.5rem 0 0 0;
    }
    
    .user-result {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
        margin-top: 0.5rem;
    }
    
    .user-preview {
        display: flex;
        align-items: center;
        gap: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        padding: 1rem;
    }
    
    .user-avatar {
        width: 3rem;
        height: 3rem;
        border-radius: 50%;
        object-fit: cover;
    }
    
    .user-info {
        flex: 1;
    }
    
    .user-info h4 {
        margin: 0;
        font-size: 1rem;
        font-weight: 500;
    }
    
    .user-id {
        margin: 0.25rem 0 0 0;
        font-size: 0.8125rem;
        color: var(--text-secondary);
    }
    
    .permissions-section {
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }
    
    .permissions-section h4 {
        margin: 0 0 0.5rem 0;
        font-size: 1rem;
        font-weight: 500;
    }
    
    .permission-option {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.75rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
    }
    
    .permission-label {
        flex: 1;
    }
    
    .permission-label label {
        font-weight: 500;
        font-size: 0.9375rem;
        display: block;
        margin-bottom: 0.25rem;
    }
    
    .permission-description {
        margin: 0;
        font-size: 0.8125rem;
        color: var(--text-secondary);
    }
    
    /* Toggle styles (reusing from existing code) */
    .toggle {
        position: relative;
        display: inline-block;
        width: 3rem;
        height: 1.5rem;
        color: grey;
    }
    
    .toggle input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    
    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: var(--bg-secondary);
        transition: .4s;
        border-radius: 1.5rem;
    }
    
    .slider:before {
        position: absolute;
        content: "";
        height: 1.125rem;
        width: 1.125rem;
        left: 0.1875rem;
        bottom: 0.1875rem;
        background-color: var(--text-secondary);
        transition: .4s;
        border-radius: 50%;
    }
    
    input:checked + .slider {
        background-color: var(--accent-color);
    }
    
    input:checked + .slider:before {
        transform: translateX(1.5rem);
        background-color: white;
    }
    
    .popup-actions {
        display: flex;
        justify-content: flex-end;
        gap: 1rem;
        padding: 1.25rem 1.5rem;
        border-top: 1px solid var(--bg-tertiary);
    }
    
    .cancel-button {
        background-color: var(--bg-tertiary);
        border: none;
        border-radius: 0.375rem;
        padding: 0.625rem 1.25rem;
        font-size: 0.9375rem;
        font-weight: 500;
        color: var(--text-secondary);
        cursor: pointer;
    }
    
    .cancel-button:hover {
        background-color: var(--bg-secondary);
        color: var(--text-primary);
    }
    
    .add-button {
        background-color: var(--accent-color);
        border: none;
        border-radius: 0.375rem;
        padding: 0.625rem 1.25rem;
        font-size: 0.9375rem;
        font-weight: 500;
        color: white;
        cursor: pointer;
    }
    
    .add-button:hover {
        background-color: var(--accent-hover);
    }
    
    .add-button:disabled {
        background-color: var(--bg-tertiary);
        color: var(--text-secondary);
        cursor: not-allowed;
    }
    
    .spinner-small {
        width: 1.25rem;
        height: 1.25rem;
        border: 0.125rem solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>