{% if session['theme'] == 'darkmode' %}
{% extends "base_dark.html" %}
{% else %}
{% extends "base.html" %}
{% endif %}

{% block title %}Benutzer bearbeiten{% endblock %}

{% block content %}
<style>
    .profile-pic-hover-effect {
        transition: box-shadow 0.3s ease-in-out;
    }

    .profile-pic-hover-effect:hover {
        box-shadow: 0 0 15px 5px rgba(0, 255, 247, 0.7);
    }

    .success-message {
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: rgba(0, 200, 0, 0.8);
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        z-index: 1000;
        opacity: 0;
        transition: opacity 0.5s ease-in-out;
    }

    .success-message.show {
        opacity: 1;
    }
</style>
<div class="content-wrapper">
    <div class="form-container">
        <label for="pfp_upload" style="cursor: pointer;">
            <img id="profile_pic_preview"
                 src="/static/pfps/{{ user['_id'] }}.png?t={{ user.get('website_accounts', {}).get('pfp_last_updated', 0) }}"
                 alt="User Profile Picture"
                 onerror="this.onerror=null; this.src='/static/user.png';"
                 class="profile-pic-hover-effect"
                 style="width: 150px; height: 150px; margin-bottom: 20px; border-radius: 50%; object-fit: cover;">
        </label>
        <form id="edit_user_form" method="POST" action="{{ url_for('edit_user', user_id=user['_id']) }}" enctype="multipart/form-data" style="width: 100%;">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <input type="file" id="pfp_upload" name="pfp" accept="image/png, image/jpeg" style="display: none;">

            <h2>Benutzer bearbeiten</h2>
            <label for="display_name">Anzeigename:</label>
            <input type="text" id="display_name" name="display_name" value="{{ user['display_name'] }}" required>
            <label for="password">Neues Passwort:</label>
            <input type="password" id="password" name="password">
            <p><strong>Berechtigungen:</strong> {{ user['permissions'] | join(', ') }}</p>
            <div style="display: flex; flex-direction: column; gap: 10px; width: 100%;">
                {% if session['theme'] == 'lightmode' %}
                <button type="submit" class="blue-button"><span>Speichern</span></button>
                <a href="/dashboard" class="black-button"><span>Zurück</span></a>
                {% else %}
                <button type="submit" class="neon-button neon1" style="width: 100%;"><span>Speichern</span></button>
                <a href="/dashboard" class="neon-button neon3" style="width: 100%; text-align: center;"><span>Zurück</span></a>
                {% endif %}
            </div>
        </form>
    </div>
</div>

<div id="success_message" class="success-message"></div>

<script>
    const pfpUploadInput = document.getElementById('pfp_upload');
    const profilePicPreview = document.getElementById('profile_pic_preview');
    const editUserForm = document.getElementById('edit_user_form');
    const successMessage = document.getElementById('success_message');
    let imageJustUploaded = false; // Flag, um zu verhindern, dass der Submit mehrfach ausgelöst wird

    // Trigger file input when image is clicked
    profilePicPreview.addEventListener('click', () => {
        pfpUploadInput.click();
    });

    // Display selected image immediately and submit the form
    pfpUploadInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                profilePicPreview.src = e.target.result;
                // Automatisches Absenden des Formulars, sobald ein Bild ausgewählt wurde
                if (!imageJustUploaded) {
                    imageJustUploaded = true;
                    editUserForm.requestSubmit();
                }
            };
            reader.readAsDataURL(file);
        }
    });

    // Handle form submission with Fetch API for instant update
    editUserForm.addEventListener('submit', async (event) => {
        event.preventDefault(); // Prevent default form submission (wird jetzt immer aufgerufen)

        const formData = new FormData(editUserForm);
        const userId = "{{ user['_id'] }}"; // Get user ID from Jinja context

        try {
            const response = await fetch(`/edit_user/${userId}`, {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const result = await response.json(); // Assuming server returns JSON
                if (result.success) {
                    // Show success message
                    successMessage.textContent = "Änderungen gespeichert!";
                    successMessage.classList.add('show');
                    setTimeout(() => {
                        successMessage.classList.remove('show');
                        imageJustUploaded = false; // Reset Flag nach erfolgreicher Speicherung
                        // Optional: Hier könntest du auch zur Dashboard-Seite weiterleiten
                        // window.location.href = "/dashboard";
                    }, 3000); // Meldung für 3 Sekunden anzeigen

                    // Update profile picture on success (sollte bereits durch die Vorschau geschehen sein)
                    if (result.pfp_url) {
                        // Append a timestamp to bust cache (wird auch beim ersten Laden gemacht)
                        profilePicPreview.src = result.pfp_url + '?t=' + new Date().getTime();
                    }
                    console.log('Profilbild erfolgreich gespeichert!');
                } else {
                    console.error('Fehler beim Speichern des Profilbildes:', result.message);
                    successMessage.textContent = 'Fehler beim Speichern!';
                    successMessage.classList.add('show');
                    setTimeout(() => {
                        successMessage.classList.remove('show');
                        imageJustUploaded = false; // Reset Flag bei Fehler
                    }, 3000);
                }
            } else {
                console.error('Serverfehler:', response.status, response.statusText);
                successMessage.textContent = 'Serverfehler!';
                successMessage.classList.add('show');
                setTimeout(() => {
                    successMessage.classList.remove('show');
                    imageJustUploaded = false; // Reset Flag bei Fehler
                }, 3000);
            }
        } catch (error) {
            console.error('Netzwerkfehler:', error);
            successMessage.textContent = 'Netzwerkfehler!';
            successMessage.classList.add('show');
            setTimeout(() => {
                successMessage.classList.remove('show');
                imageJustUploaded = false; // Reset Flag bei Fehler
            }, 3000);
        }
    });
</script>
{% endblock %}