<script lang="ts">
    import { onMount, onDestroy } from 'svelte';
    import Notification from '$lib/components/notifications/Popup.svelte';
    import { discordAuthUrl } from '$lib/config.json';
    import { discordDataStore, discordTokenStore, authTokenStore, TAServerPort, TAServerUrl, client } from '$lib/stores';
    import { TAClient, Response_ResponseType } from 'moons-ta-client';
    import { v4 as uuidv4 } from "uuid";

    let showLoginNotification: boolean = false;
    let showCreateTokenModal: boolean = false;
    let showTokenCreatedModal: boolean = false;
    let error: string = "";
    let isLoggedIn: boolean = false;
    let loading: boolean = true;
    let authTokens: any[] = [];
    let newBotName: string = "";
    let newlyCreatedToken: string = "";
    let creatingToken: boolean = false;
    
    // Change to an object for better reactivity
    let copyClicked: Record<string, boolean> = {};

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

    onMount(async () => {
        try {
            // Check if user is logged in
            isLoggedIn = !!$authTokenStore && !!$discordDataStore;

            if (!isLoggedIn) {
                showLoginNotification = true;
                loading = false;
                return;
            }            
            
            try {
                if(!client.isConnected) {
                    const connectResult = await client.connect($TAServerUrl, $TAServerPort);

                    if (connectResult.details.oneofKind === "connect" && connectResult.type === Response_ResponseType.Fail) {
                        error = "Failed to connect to server";
                        loading = false;
                    }
                }
                
                const tokens = await client.getBotTokensForUser($discordDataStore.id);
                authTokens = (tokens as any).details.getBotTokensForUser?.botUsers || [];
                loading = false;
            } catch (connErr) {
                console.error('TAClient connection error:', connErr);
                error = "Connection error";
                loading = false;
            }
        } catch (e) {
            console.error('Failed to fetch auth tokens', e);
            error = "Failed to fetch auth tokens";
            loading = false;
        }
    });

    function closeNotification() {
        showLoginNotification = false;
    }
    
    function copyToClipboard(text: string) {
        // Set the copy status to true in the object
        copyClicked = { ...copyClicked, [text]: true };
        
        navigator.clipboard.writeText(text)
            .then(() => {
                console.log('Copied to clipboard!');
            })
            .catch(err => {
                console.error('Failed to copy: ', err);
            });
            
        // Reset after timeout
        setTimeout(() => {
            copyClicked = { ...copyClicked, [text]: false };
        }, 3000);
    }

    function openCreateTokenModal() {
        newBotName = "";
        showCreateTokenModal = true;
    }

    function closeCreateTokenModal() {
        showCreateTokenModal = false;
    }

    function closeTokenCreatedModal() {
        showTokenCreatedModal = false;
    }

    async function createBotToken() {
        if (!newBotName.trim()) return;
        
        creatingToken = true;
        try {
            const createTokenRes = await client.generateBotToken(newBotName.trim());

            // Set the new bot token
            newlyCreatedToken = (createTokenRes as any).details.generateBotToken?.botToken;
            
            // Refresh token list
            const tokens = await client.getBotTokensForUser($discordDataStore.id);
            authTokens = (tokens as any).details.getBotTokensForUser?.botUsers || [];
            
            // Close create modal and show the created token modal
            closeCreateTokenModal();
            showTokenCreatedModal = true;
        } catch (err) {
            console.error('Failed to create bot token:', err);
            error = "Failed to create bot token";
        } finally {
            creatingToken = false;
        }
    }

    async function deleteBotToken(tokenId: string) {
        try {
            await client.revokeBotToken(tokenId);
            // Refresh the list after deletion
            const tokens = await client.getBotTokensForUser($discordDataStore.id);
            authTokens = (tokens as any).details.getBotTokensForUser?.botUsers || [];
        } catch (err) {
            console.error('Failed to delete bot token:', err);
            error = "Failed to delete bot token";
        }
    }
</script>

<main>
    <section class="hero-section">
        <div class="content">
            <h1>Bot Tokens</h1>
            <p>Manage your tokens for API and NPM client access</p>
        </div>
    </section>

    {#if error}
        <div class="error-message">
            <i class="material-icons">error</i>
            <p>{error}</p>
        </div>
    {/if}

    <section class="tokens-section">
        <div class="section-header">
            <div class="spacer"></div>
            {#if isLoggedIn && !error}
                <button class="create-token-btn" on:click={openCreateTokenModal}>
                    <i class="material-icons">add</i>
                    <span>Create Bot Token</span>
                </button>
            {/if}
        </div>

        {#if loading}
            <div class="loading-container">
                <div class="loading-spinner"></div>
                <p>Loading tokens...</p>
            </div>
        {:else if error}
            <div class="error-container">
                <div class="error-icon">
                    <i class="material-icons">error_outline</i>
                </div>
                <p>Failed to load tokens. Please try again later.</p>
                <button class="retry-button" on:click={() => window.location.reload()}>
                    <i class="material-icons">refresh</i>
                    Retry
                </button>
            </div>
        {:else if authTokens.length === 0}
            <div class="empty-container">
                <div class="empty-icon">
                    <i class="material-icons">vpn_key</i>
                </div>
                <p>No bot tokens found.</p>
                {#if isLoggedIn}
                    <button class="create-first-token-btn" on:click={openCreateTokenModal}>
                        <i class="material-icons">add_circle</i>
                        Create Your First Bot Token
                    </button>
                {/if}
            </div>
        {:else}
            <div class="tokens-table-container">
                <table class="tokens-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Token ID</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {#each authTokens as token}
                            <tr>
                                <td class="token-name">{token.username}</td>
                                <td class="token-guid">
                                    <div class="guid-container">
                                        <span class="guid-text">{token.guid}</span>
                                        <button class="copy-button" on:click={() => copyToClipboard(token.guid)}>
                                            {#if copyClicked[token.guid]}
                                                <i class="material-icons">check_circle</i>
                                            {:else}
                                                <i class="material-icons">content_copy</i>
                                            {/if}
                                        </button>
                                    </div>
                                </td>
                                <td class="token-actions">
                                    <button class="delete-button" on:click={() => deleteBotToken(token.guid)}>
                                        <i class="material-icons">delete</i>
                                    </button>
                                </td>
                            </tr>
                        {/each}
                    </tbody>
                </table>
            </div>
        {/if}
    </section>

    <!-- Create Token Modal -->
    {#if showCreateTokenModal}
        <!-- svelte-ignore a11y-no-static-element-interactions -->
        <!-- svelte-ignore a11y-click-events-have-key-events -->
        <div class="modal-backdrop" on:click={closeCreateTokenModal}></div>
        <div class="modal-container">
            <!-- svelte-ignore a11y-click-events-have-key-events -->
            <!-- svelte-ignore a11y-no-static-element-interactions -->
            <div class="modal-content" on:click|stopPropagation>
                <div class="modal-header">
                    <h2>Create Bot Token</h2>
                    <button class="close-btn" on:click={closeCreateTokenModal}>
                        <i class="material-icons">close</i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="botName">Bot Name</label>
                        <input 
                            type="text" 
                            id="botName" 
                            bind:value={newBotName} 
                            placeholder="Enter a name for your bot"
                        />
                    </div>
                    <p class="token-warning">
                        <i class="material-icons">warning</i>
                        After creation, the token will be shown only once. Please save it in a secure location.
                    </p>
                </div>
                <div class="modal-footer">
                    <button class="cancel-btn" on:click={closeCreateTokenModal}>Cancel</button>
                    <button 
                        class="create-btn" 
                        on:click={createBotToken} 
                        disabled={!newBotName.trim() || creatingToken}
                    >
                        {#if creatingToken}
                            <span class="btn-spinner"></span>
                        {:else}
                            <i class="material-icons">vpn_key</i>
                        {/if}
                        Create Token
                    </button>
                </div>
            </div>
        </div>
    {/if}

    <!-- Token Created Modal -->
    <!-- svelte-ignore a11y-no-static-element-interactions -->
    {#if showTokenCreatedModal}
        <!-- svelte-ignore a11y-click-events-have-key-events -->
        <div class="modal-backdrop" on:click={closeTokenCreatedModal}></div>
        <!-- svelte-ignore a11y-click-events-have-key-events -->
        <div class="modal-container">
            <!-- svelte-ignore a11y-no-static-element-interactions -->
            <div class="modal-content" on:click|stopPropagation>
                <div class="modal-header">
                    <h2>Bot Token Created</h2>
                    <button class="close-btn" on:click={closeTokenCreatedModal}>
                        <i class="material-icons">close</i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="token-created-message">
                        <i class="material-icons success-icon">check_circle</i>
                        <p>Your bot token has been created successfully!</p>
                    </div>
                    <div class="form-group">
                        <!-- svelte-ignore a11y-label-has-associated-control -->
                        <label>Token (copy this now, it won't be shown again and cannot be regenerated)</label>
                        <div class="token-display">
                            <input 
                                type="text" 
                                readonly 
                                value={newlyCreatedToken} 
                                class="token-input"
                            />
                            <button class="copy-token-btn" on:click={() => copyToClipboard(newlyCreatedToken)}>
                                {#if copyClicked[newlyCreatedToken]}
                                    <i class="material-icons">check_circle</i>
                                {:else}
                                    <i class="material-icons">content_copy</i>
                                {/if}
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="create-btn" on:click={closeTokenCreatedModal}>
                        <i class="material-icons">check</i>
                        Done
                    </button>
                </div>
            </div>
        </div>
    {/if}

    <Notification
        bind:open={showLoginNotification}
        message="You need to be logged in with Discord to manage bot tokens"
        icon="login"
        iconColor="primary"
        buttons={[
            {
                text: "Login with Discord",
                type: "primary",
                href: discordAuthUrl,
                icon: "discord",
                color: "primary"
            },
            {
                text: "Back to Home",
                type: "outlined",
                href: "/",
                icon: "home",
                color: "secondary"
            }
        ]}
        on:close={closeNotification}
    />
</main>

<style>
    /* Main content */
    main {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 2rem 1.5rem;
        max-width: 1200px;
        margin: 0 auto;
        width: 100%;
    }

    /* Hero section */
    .hero-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-align: center;
        padding: 1rem 0;
        width: 100%;
    }

    .content {
        max-width: 800px;
    }

    .hero-section h1 {
        font-size: 3.5rem;
        background: linear-gradient(90deg, var(--accent-color), var(--accent-hover));
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        text-shadow: 0 0 15px var(--accent-glow);
    }

    .hero-section p {
        font-size: 1.25rem;
        color: var(--text-secondary);
        margin-bottom: 2rem;
        line-height: 1.6;
    }

    /* Section header with Create Token button */
    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        margin-bottom: 1.5rem;
    }

    .spacer {
        flex: 1;
    }

    .create-token-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.25rem;
        background: linear-gradient(135deg, var(--accent-color), var(--accent-hover));
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        font-size: 1rem;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    .create-token-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2), 0 0 10px var(--accent-glow);
    }

    .create-token-btn:active {
        transform: translateY(0);
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }

    .create-token-btn i {
        font-size: 1.25rem;
    }

    .create-first-token-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-top: 1.5rem;
        padding: 0.75rem 1.5rem;
        background: linear-gradient(135deg, var(--accent-color), var(--accent-hover));
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    .create-first-token-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2), 0 0 10px var(--accent-glow);
    }

    /* Error message */
    .error-message {
        display: flex;
        align-items: center;
        background-color: rgba(255, 0, 0, 0.1);
        border-left: 4px solid #ff5555;
        padding: 1rem;
        border-radius: 4px;
        margin-bottom: 2rem;
        width: 100%;
    }

    .error-message i {
        color: #ff5555;
        margin-right: 0.75rem;
    }

    /* Tokens section */
    .tokens-section {
        width: 100%;
        margin-top: 2rem;
    }

    /* Tokens table */
    .tokens-table-container {
        width: 100%;
        overflow-x: auto;
        background-color: var(--bg-secondary);
        border-radius: 12px;
        border: 1px solid var(--border-color);
    }

    .tokens-table {
        width: 100%;
        border-collapse: collapse;
    }

    .tokens-table th {
        text-align: left;
        padding: 1rem;
        font-weight: 600;
        color: var(--text-secondary);
        border-bottom: 1px solid var(--border-color);
    }

    .tokens-table td {
        padding: 1rem;
        border-bottom: 1px solid var(--border-color);
    }

    .tokens-table tr:last-child td {
        border-bottom: none;
    }

    .token-name {
        font-weight: 500;
    }

    .token-guid {
        font-family: monospace;
        color: var(--text-secondary);
    }

    .guid-container {
        display: flex;
        align-items: center;
    }

    .guid-text {
        max-width: 3000px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .copy-button {
        background: none;
        border: none;
        cursor: pointer;
        color: var(--text-secondary);
        padding: 0;
        margin-left: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0.5;
        transition: opacity 0.2s;
    }

    .copy-button:hover {
        opacity: 1;
    }

    .copy-button i {
        font-size: 0.875rem;
    }

    .token-actions {
        text-align: right;
    }

    .delete-button {
        background: none;
        border: none;
        cursor: pointer;
        color: #ff5555;
        padding: 0.5rem;
        border-radius: 4px;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .delete-button:hover {
        background-color: rgba(255, 85, 85, 0.1);
    }

    /* Loading, error, and empty states */
    .loading-container,
    .error-container,
    .empty-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 4rem 2rem;
        text-align: center;
        width: 100%;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 4px solid rgba(var(--accent-color-rgb), 0.2);
        border-radius: 50%;
        border-top-color: var(--accent-color);
        animation: spin 1s linear infinite;
        margin-bottom: 1.5rem;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .error-icon,
    .empty-icon {
        font-size: 3rem;
        color: var(--accent-color);
        margin-bottom: 1.5rem;
    }

    .error-icon i,
    .empty-icon i {
        font-size: 3.5rem;
    }

    .retry-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-top: 1.5rem;
        padding: 0.75rem 1.5rem;
        background-color: var(--accent-color);
        color: white;
        border: none;
        border-radius: 4px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

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

    /* Modal styles */
    .modal-backdrop {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.7);
        backdrop-filter: blur(4px);
        z-index: 1000;
        animation: fadeIn 0.2s ease;
    }

    .modal-container {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1001;
        padding: 1rem;
    }

    .modal-content {
        background-color: var(--bg-primary);
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        width: 100%;
        max-width: 500px;
        max-height: 90vh;
        overflow-y: auto;
        animation: modalSlideIn 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--border-color);
    }

    .modal-header h2 {
        font-size: 1.5rem;
        margin: 0;
        color: var(--text-primary);
    }

    .close-btn {
        background: none;
        border: none;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 0.5rem;
        margin: -0.5rem;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
    }

    .close-btn:hover {
        background-color: rgba(0, 0, 0, 0.1);
        color: var(--text-primary);
    }

    .modal-body {
        padding: 1.5rem;
    }

    .form-group {
        margin-bottom: 1.5rem;
    }

    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
        color: var(--text-secondary);
    }

    .form-group input[type="text"] {
        width: 85%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background-color: var(--bg-secondary);
        color: var(--text-primary);
        font-size: 1rem;
        transition: all 0.2s;
    }

    .form-group input[type="text"]:focus {
        border-color: var(--accent-color);
        box-shadow: 0 0 0 2px rgba(var(--accent-color-rgb), 0.2);
        outline: none;
    }

    .token-warning {
        display: flex;
        align-items: flex-start;
        gap: 0.5rem;
        padding: 1rem;
        background-color: rgba(255, 193, 7, 0.1);
        border-left: 4px solid #ffc107;
        border-radius: 4px;
        color: var(--text-secondary);
        font-size: 0.875rem;
    }

    .token-warning i {
        color: #ffc107;
        font-size: 1.25rem;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        padding: 1.25rem 1.5rem;
        border-top: 1px solid var(--border-color);
        gap: 1rem;
    }

    .cancel-btn {
        padding: 0.75rem 1.25rem;
        background-color: transparent;
        border: 1px solid var(--border-color);
        color: var(--text-secondary);
        border-radius: 8px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
    }

    .cancel-btn:hover {
        background-color: var(--bg-secondary);
        color: var(--text-primary);
    }

    .create-btn {
        padding: 0.75rem 1.5rem;
        background: linear-gradient(135deg, var(--accent-color), var(--accent-hover));
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .create-btn:hover:not(:disabled) {
        box-shadow: 0 0 15px var(--accent-glow);
        transform: translateY(-2px);
    }

    .create-btn:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    .btn-spinner {
        width: 1rem;
        height: 1rem;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 1s linear infinite;
    }

    /* Token Created Modal specific styles */
    .token-created-message {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 1.5rem;
    }

    .success-icon {
        color: #4caf50;
        font-size: 1.5rem;
    }

    .token-display {
        position: relative;
    }

    .token-input {
        width: 100%;
        padding: 0.75rem 1rem;
        border: 1px solid var(--border-color);
        border-radius: 8px;
        background-color: var(--bg-secondary);
        color: var(--text-primary);
        font-family: monospace;
        font-size: 0.875rem;
        padding-right: 3rem;
    }

    .copy-token-btn {
        position: absolute;
        right: 0.5rem;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: var(--accent-color);
        cursor: pointer;
        padding: 0.5rem;
        border-radius: 4px;
        transition: all 0.2s;
    }

    .copy-token-btn:hover {
        background-color: rgba(var(--accent-color-rgb), 0.1);
    }

    /* Animations */
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    @keyframes modalSlideIn {
        from {
            opacity: 0;
            transform: translateY(-30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Responsive design */
    @media (max-width: 768px) {
        .hero-section h1 {
            font-size: 2.5rem;
        }

        .hero-section p {
            font-size: 1rem;
        }
        
        .guid-text {
            max-width: 120px;
        }
    }

    @media (max-width: 480px) {
        .hero-section h1 {
            font-size: 2rem;
        }
        
        .tokens-table th,
        .tokens-table td {
            padding: 0.75rem;
        }
        
        .guid-text {
            max-width: 80px;
        }
        
        .create-token-btn span {
            display: none;
        }
    }
</style>