{% extends "base.html" %}

{% block title %}User Credentials{% endblock %}
{% block page_id %}users{% endblock %}
{% block page_title %}User Credentials{% endblock %}
{% block eyebrow %}Management{% endblock %}

{% block content %}
    <!-- Flash Messages Container -->
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            <div class="flash-container">
                {% for category, message in messages %}
                    <div class="flash {{ category }}">
                        {{ message }}
                        <button class="flash-close" onclick="this.parentElement.remove()">&times;</button>
                    </div>
                {% endfor %}
            </div>
        {% endif %}
    {% endwith %}

    {% if error %}
    <div class="flash-container">
        <div class="flash error">
            Error loading users: {{ error }}
            <button class="flash-close" onclick="this.parentElement.remove()">&times;</button>
        </div>
    </div>
    {% endif %}

    <section class="panel-stack">
        <article class="glass-card panel-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">All Users</p>
                    <h3>Manage User Credentials</h3>
                </div>
                <div style="display:flex;align-items:center;gap:12px;">
                    <span class="pill">{{ users|length }} users</span>
                    <button onclick="openAddUserModal()" class="uc-add-btn" type="button">+ Add User</button>
                </div>
            </div>

            <div class="users-table-wrapper">
                <table class="users-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Role</th>
                            <th>Password</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for user in users %}
                        <tr data-user-id="{{ user.id }}">
                            <td class="user-id">{{ user.id }}</td>
                            <td class="user-name">{{ user.name or "N/A" }}</td>
                            <td class="username">{{ user.username }}</td>
                            <td class="user-email">{{ user.email or "N/A" }}</td>
                            <td class="user-phone">{{ user.phone or "N/A" }}</td>
                            <td class="user-role">
                                <select class="role-select" data-user-id="{{ user.id }}" data-current-role="{{ user.role or 'photographer' }}">
                                    <option value="admin" {% if user.role == 'admin' %}selected{% endif %}>Admin</option>
                                    <option value="photographer" {% if user.role != 'admin' %}selected{% endif %}>Photographer</option>
                                </select>
                            </td>
                            <td class="password-cell">
                                <input type="password" id="pass_{{ user.id }}" class="password-input" placeholder="Enter new password">
                                <button class="toggle-password-btn" onclick="togglePasswordVisibility({{ user.id }})" type="button">👁️</button>
                            </td>
                            <td class="actions-cell">
                                <button class="update-password-btn" onclick="updatePassword({{ user.id }})" type="button">
                                    Update Password
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </article>
    </section>

    <!-- ADD USER MODAL -->
    <div id="addUserModal" class="uc-modal">
        <div class="uc-modal-content">
            <div class="uc-modal-header">
                <h3>Add New User</h3>
                <button class="uc-modal-close" onclick="closeAddUserModal()">&times;</button>
            </div>
            <div class="uc-modal-body">
                <div class="uc-field">
                    <label>Name</label>
                    <input type="text" id="newName" placeholder="e.g. John Photographer" autocomplete="off">
                </div>
                <div class="uc-field">
                    <label>Username <span style="color:#e53e3e;">*</span></label>
                    <input type="text" id="newUsername" placeholder="e.g. photographer3" autocomplete="off">
                </div>
                <div class="uc-field">
                    <label>Email</label>
                    <input type="email" id="newEmail" placeholder="e.g. photo@example.com" autocomplete="off">
                </div>
                <div class="uc-field">
                    <label>Phone</label>
                    <input type="text" id="newPhone" placeholder="e.g. 9876543210" autocomplete="off">
                </div>
                <div class="uc-field">
                    <label>Password <span style="color:#e53e3e;">*</span></label>
                    <input type="password" id="newPassword" placeholder="Min 6 characters" autocomplete="off">
                </div>
                <div class="uc-field">
                    <label>Role <span style="color:#e53e3e;">*</span></label>
                    <select id="newRole">
                        <option value="photographer">Photographer</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
                <div class="uc-modal-buttons">
                    <button class="uc-cancel-btn" onclick="closeAddUserModal()">Cancel</button>
                    <button class="uc-save-btn" onclick="submitAddUser()">Add User</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block head %}
<style>
    /* Flash message popup styling */
    .flash-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        max-width: 400px;
    }

    .flash {
        padding: 14px 20px;
        border-radius: 10px;
        margin-bottom: 12px;
        color: #fff;
        font-weight: 500;
        font-size: 14px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        animation: slideIn 0.3s ease;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .flash.error {
        background: linear-gradient(135deg, #dc2626, #b91c1c);
    }

    .flash.success {
        background: linear-gradient(135deg, #16a34a, #15803d);
    }

    .flash-close {
        background: transparent;
        border: none;
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin-left: 12px;
        padding: 0;
        width: 24px;
        height: 24px;
        line-height: 1;
        opacity: 0.8;
        transition: opacity 0.2s;
    }

    .flash-close:hover {
        opacity: 1;
    }

    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateX(20px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }

    @keyframes slideOut {
        from {
            opacity: 1;
            transform: translateX(0);
        }
        to {
            opacity: 0;
            transform: translateX(20px);
        }
    }

    .flash.removing {
        animation: slideOut 0.3s ease forwards;
    }

    /* Users Table Styling */
    .users-table-wrapper {
        overflow-x: auto;
        margin-top: 20px;
    }

    .users-table {
        width: 100%;
        border-collapse: collapse;
        background: #ffffff;
        border-radius: 12px;
        overflow: hidden;
        color: #0f172a !important;
    }

    .users-table thead {
        background: linear-gradient(135deg, #0f2b3d, #1b4f6e);
        color: #ffffff !important;
    }

    .users-table th {
        padding: 14px 12px;
        text-align: left;
        font-weight: 600;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #ffffff !important;
    }

    .users-table td {
        padding: 12px;
        border-bottom: 1px solid #e2e8f0;
        vertical-align: middle;
        color: #0f172a !important;
        background: #ffffff !important;
    }

    .users-table tbody tr:hover {
        background: #f8fafc !important;
    }

    .users-table tbody tr:hover td {
        background: #f8fafc !important;
        color: #0f172a !important;
    }

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

    .user-id {
        font-weight: 700;
        color: #0f172a !important;
        font-size: 14px;
    }

    .user-name {
        font-weight: 600;
        color: #0f172a !important;
    }

    .username {
        color: #0f172a !important;
        font-family: monospace;
        font-size: 13px;
    }

    .user-email {
        color: #0f172a !important;
    }

    .user-phone {
        color: #0f172a !important;
        font-size: 13px;
    }

    /* Role Select */
    .role-select {
        padding: 6px 10px;
        border-radius: 8px;
        border: 1.5px solid #cbd5e1;
        background: #ffffff;
        color: #0f172a;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
    }

    .role-select:hover {
        border-color: #2c7da0;
    }

    .role-select:focus {
        outline: none;
        border-color: #2c7da0;
        box-shadow: 0 0 0 3px rgba(44, 125, 160, 0.1);
    }

    /* Password Input */
    .password-cell {
        position: relative;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .password-input {
        flex: 1;
        padding: 8px 12px;
        border-radius: 8px;
        border: 1.5px solid #cbd5e1;
        background: #ffffff;
        color: #0f172a;
        font-size: 13px;
        font-family: monospace;
        transition: all 0.2s;
    }

    .password-input:focus {
        outline: none;
        border-color: #2c7da0;
        box-shadow: 0 0 0 3px rgba(44, 125, 160, 0.1);
    }

    .password-input::placeholder {
        color: #94a3b8;
    }

    .toggle-password-btn {
        background: transparent;
        border: none;
        cursor: pointer;
        font-size: 16px;
        padding: 4px;
        transition: transform 0.2s;
    }

    .toggle-password-btn:hover {
        transform: scale(1.2);
    }

    /* Action Buttons */
    .actions-cell {
        white-space: nowrap;
    }

    .update-password-btn {
        padding: 8px 16px;
        border-radius: 8px;
        border: none;
        background: linear-gradient(135deg, #2c7da0, #1f5068);
        color: #ffffff;
        font-weight: 600;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.2s;
        white-space: nowrap;
    }

    .update-password-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(44, 125, 160, 0.3);
    }

    .update-password-btn:active {
        transform: translateY(0);
    }

    /* Add User Button */
    .uc-add-btn {
        padding: 9px 18px;
        background: rebeccapurple;
        color: black;
        border: none;
        border-radius: 10px;
        font-weight: 700;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .uc-add-btn:hover { background: #1a5f7a; transform: translateY(-1px); }

    /* Modal */
    .uc-modal {
        display: none; position: fixed; inset: 0;
        background: rgba(15,23,42,0.65); backdrop-filter: blur(6px);
        z-index: 1000; align-items: center; justify-content: center; padding: 16px;
    }
    .uc-modal.active { display: flex; }

    .uc-modal-content {
        background: #ffffff; border-radius: 16px; width: 100%; max-width: 440px;
        box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden;
        animation: ucIn 0.2s ease;
    }
    @keyframes ucIn { from { opacity:0; transform:translateY(-16px) scale(0.97); } to { opacity:1; transform:translateY(0) scale(1); } }

    .uc-modal-header {
        background: linear-gradient(135deg, #0f2b3d, #1b5e7a);
        padding: 16px 20px; display: flex; align-items: center; justify-content: space-between;
    }
    .uc-modal-header h3 { margin: 0; color: #ffffff !important; font-size: 16px; font-weight: 700; }
    .uc-modal-close {
        background: rgba(255,255,255,0.15); border: 1.5px solid rgba(255,255,255,0.3);
        color: #ffffff; width: 32px; height: 32px; border-radius: 8px;
        cursor: pointer; font-size: 18px; display: flex; align-items: center; justify-content: center; padding: 0;
    }
    .uc-modal-close:hover { background: rgba(255,255,255,0.3); }

    .uc-modal-body { padding: 20px; display: flex; flex-direction: column; gap: 14px; }

    .uc-field { display: flex; flex-direction: column; gap: 5px; }
    .uc-field label { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #475569; }
    .uc-field input, .uc-field select {
        padding: 10px 14px; border: 1.5px solid #e2e8f0; border-radius: 10px;
        font-size: 14px; color: #0f172a; background: #f8fafc; transition: all 0.2s;
    }
    .uc-field input:focus, .uc-field select:focus {
        outline: none; border-color: #2c7da0; background: #ffffff;
        box-shadow: 0 0 0 3px rgba(44,125,160,0.15);
    }
    .uc-field input::placeholder { color: #b0bec5; }

    .uc-modal-buttons { display: flex; gap: 10px; padding-top: 4px; }
    .uc-save-btn {
        flex: 1; padding: 12px 20px; background: #2c7da0;
        color: blue !important; border: none; border-radius: 10px;
        font-size: 14px; font-weight: 700; cursor: pointer; transition: all 0.2s;
    }
    .uc-save-btn:hover { background: #1a5f7a; transform: translateY(-1px); }
    .uc-cancel-btn {
        flex: 1; padding: 12px 20px; background: #ffffff;
        color: #475569 !important; border: 1.5px solid #cbd5e1;
        border-radius: 10px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.2s;
    }
    .uc-cancel-btn:hover { background: #f1f5f9; border-color: #94a3b8; }

    /* Responsive */
    @media (max-width: 1024px) {
        .users-table {
            font-size: 12px;
        }

        .users-table th,
        .users-table td {
            padding: 8px 6px;
        }
    }
</style>
{% endblock %}

{% block scripts %}
<script>
    // ── Add User Modal ────────────────────────────────────────────────────────
    function openAddUserModal() {
        document.getElementById('newName').value = '';
        document.getElementById('newUsername').value = '';
        document.getElementById('newEmail').value = '';
        document.getElementById('newPhone').value = '';
        document.getElementById('newPassword').value = '';
        document.getElementById('newRole').value = 'photographer';
        document.getElementById('addUserModal').classList.add('active');
        setTimeout(() => document.getElementById('newName').focus(), 100);
    }

    function closeAddUserModal() {
        document.getElementById('addUserModal').classList.remove('active');
    }

    async function submitAddUser() {
        const username = document.getElementById('newUsername').value.trim();
        const password = document.getElementById('newPassword').value.trim();
        const name = document.getElementById('newName').value.trim();
        const email = document.getElementById('newEmail').value.trim();
        const phone = document.getElementById('newPhone').value.trim();
        const role = document.getElementById('newRole').value;

        if (!username) { showFlashMessage('Username is required.', 'error'); return; }
        if (!password) { showFlashMessage('Password is required.', 'error'); return; }
        if (password.length < 6) { showFlashMessage('Password must be at least 6 characters.', 'error'); return; }

        try {
            const res = await fetch('/admin/api/users/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password, name, email, phone, role })
            });
            const data = await res.json();

            if (!res.ok || data.error) {
                showFlashMessage(data.error || 'Failed to add user.', 'error');
                return;
            }

            showFlashMessage(`User "${username}" added successfully!`, 'success');
            closeAddUserModal();
            setTimeout(() => window.location.reload(), 1200);
        } catch (err) {
            showFlashMessage('Failed to add user. Please try again.', 'error');
        }
    }

    // Close modal on backdrop click
    document.getElementById('addUserModal').addEventListener('click', function(e) {
        if (e.target === this) closeAddUserModal();
    });

    // Enter key support
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape') closeAddUserModal();
    });

    // ── Toggle password ───────────────────────────────────────────────────────
    function togglePasswordVisibility(userId) {
        const passwordInput = document.getElementById("pass_" + userId);
        if (passwordInput.type === "password") {
            passwordInput.type = "text";
        } else {
            passwordInput.type = "password";
        }
    }

    // Update password function
    async function updatePassword(userId) {
        const passwordInput = document.getElementById("pass_" + userId);
        const password = passwordInput.value.trim();

        if (!password) {
            showFlashMessage("Please enter a new password.", "error");
            return;
        }

        if (password.length < 6) {
            showFlashMessage("Password must be at least 6 characters.", "error");
            return;
        }

        try {
            const res = await fetch(`/admin/api/users/${userId}/password`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ password: password })
            });

            const data = await res.json();

            if (!res.ok || data.error) {
                showFlashMessage(data.error || "Failed to update password.", "error");
                return;
            }

            showFlashMessage("Password updated successfully!", "success");
            passwordInput.value = "";
        } catch (err) {
            console.error("Update password error:", err);
            showFlashMessage("Failed to update password. Please try again.", "error");
        }
    }

    // Update role function
    async function updateRole(userId, newRole) {
        try {
            const res = await fetch(`/admin/api/users/${userId}/role`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ role: newRole })
            });

            const data = await res.json();

            if (!res.ok || data.error) {
                showFlashMessage(data.error || "Failed to update role.", "error");
                return;
            }

            showFlashMessage(`Role updated to ${newRole}!`, "success");
        } catch (err) {
            console.error("Update role error:", err);
            showFlashMessage("Failed to update role. Please try again.", "error");
        }
    }

    // Flash message function
    function showFlashMessage(message, type = "success") {
        let container = document.querySelector(".flash-container");
        if (!container) {
            container = document.createElement("div");
            container.className = "flash-container";
            document.querySelector(".admin-main").prepend(container);
        }

        const flash = document.createElement("div");
        flash.className = `flash ${type}`;
        flash.innerHTML = `
            ${message}
            <button class="flash-close" onclick="this.parentElement.remove()">&times;</button>
        `;

        container.appendChild(flash);

        setTimeout(() => {
            flash.classList.add("removing");
            setTimeout(() => flash.remove(), 300);
        }, 5000);
    }

    // Bind role select change events
    document.addEventListener("DOMContentLoaded", () => {
        const roleSelects = document.querySelectorAll(".role-select");
        roleSelects.forEach(select => {
            select.addEventListener("change", (e) => {
                const userId = e.target.dataset.userId;
                const newRole = e.target.value;
                updateRole(userId, newRole);
            });
        });
    });
</script>
{% endblock %}