<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Set Password</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 600px;
            margin: 2rem auto;
            padding: 2rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 1.5rem;
            text-align: center;
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        input[type="password"] {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
            box-sizing: border-box;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            width: 100%;
            transition: background-color 0.2s;
        }
        button:hover {
            background-color: #2980b9;
        }
        .message {
            padding: 1rem;
            border-radius: 4px;
            margin-bottom: 1rem;
        }
        .error-message {
            background-color: #fde8e8;
            color: #c53030;
            border: 1px solid #fbd5d5;
        }
        .success-message {
            background-color: #def7ec;
            color: #03543f;
            border: 1px solid #bcf0da;
        }
        .hint {
            font-size: 0.9rem;
            color: #555;
            margin-bottom: 1rem;
        }
        @media (max-width: 640px) {
            .container {
                margin: 1rem;
                padding: 1rem;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h1>Set Your Password</h1>

    {% if validlink %}
        <p class="hint">
            Choose a strong password to complete your registration.
        </p>

        <div id="message-container" class="message" style="display: none;"></div>

        <form method="post" id="set-password-form" action="{% url 'rest_set_password' %}">
            {% csrf_token %}

            <div class="form-group">
                <label for="id_new_password1">New Password</label>
                <input type="password" name="new_password1" id="id_new_password1" required>
            </div>

            <div class="form-group">
                <label for="id_new_password2">Confirm New Password</label>
                <input type="password" name="new_password2" id="id_new_password2" required>
            </div>

            <button type="submit">Set Password</button>
        </form>
    {% else %}
        <div class="message error-message">
            <p>
                This password setup link is invalid or has expired. It may have already been used.
                Please contact the administrator who invited you for a new link.
            </p>
        </div>
    {% endif %}
</div>

{% if validlink %}
<script>
    (function () {
        const form = document.getElementById('set-password-form');
        const messageContainer = document.getElementById('message-container');

        function showMessage(type, text) {
            if (!messageContainer) return;
            messageContainer.style.display = 'block';
            messageContainer.className = 'message ' + (type === 'error' ? 'error-message' : 'success-message');
            messageContainer.textContent = text;
        }

        if (form) {
            form.addEventListener('submit', function (e) {
                e.preventDefault();

                const password1 = document.getElementById('id_new_password1').value;
                const password2 = document.getElementById('id_new_password2').value;

                if (!password1 || !password2) {
                    showMessage('error', 'Please fill in both password fields.');
                    return;
                }
                if (password1 !== password2) {
                    showMessage('error', 'The two password fields did not match.');
                    return;
                }

                const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

                fetch(form.action, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': csrftoken,
                        'Accept': 'application/json'
                    },
                    body: new FormData(form)
                })
                .then(async response => {
                    const isJson = (response.headers.get('content-type') || '').includes('application/json');
                    const data = isJson ? await response.json().catch(() => ({})) : {};

                    if (!response.ok) {
                        const detail = data.detail || 'Unable to set password. Please try again.';
                        showMessage('error', detail);
                        return;
                    }

                    // Handle MFA-required responses gracefully
                    if (data && data.mfa_setup_required) {
                        showMessage(
                            'success',
                            data.detail || 'Password set. Additional security setup (MFA) is required in your application.'
                        );
                        return;
                    }

                    showMessage('success', (data && data.detail) || 'Your password has been set successfully.');
                })
                .catch(() => {
                    showMessage('error', 'An unexpected error occurred. Please try again.');
                });
            });
        }
    })();
</script>
{% endif %}
</body>
</html>


