<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 300px;
            text-align: center;
        }

        .container h2 {
            margin-bottom: 20px;
        }

        .otp-input {
            display: flex;
            justify-content: space-between;
        }

        .otp-input input {
            width: 40px;
            height: 40px;
            font-size: 18px;
            text-align: center;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        button {
            margin-top: 20px;
            padding: 10px 20px;
            background-color: orange;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:disabled {
            background-color: #cccccc;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2>Login with OTP</h2>
        <form id="otp-form" method="POST">
            {% csrf_token %}
            <div class="otp-input">
                <input type="text" name="a" maxlength="1" required>
                <input type="text" name="b" maxlength="1" required>
                <input type="text" name="c" maxlength="1" required>
                <input type="text" name="d" maxlength="1" required>
                <input type="text" name="e" maxlength="1" required>
                <input type="text" name="f" maxlength="1" required>
            </div>
            <button type="submit">Verify OTP</button>
            {% if error %}
            <p>{{ error }}</p>
            {% endif %}
        </form>
    </div>

    <script>
        const inputs = document.querySelectorAll('.otp-input input');
        const button = document.querySelector('button');

        // Automatically move to the next input when typing
        inputs.forEach((input, index) => {
            input.addEventListener('input', () => {
                if (input.value.length === 1 && index < inputs.length - 1) {
                    inputs[index + 1].focus();
                }
                checkAllInputs();
            });
            input.addEventListener('keydown', (e) => {
                if (e.key === 'Backspace' && input.value.length === 0 && index > 0) {
                    inputs[index - 1].focus();
                }
            });
        });

        // Check if all inputs are filled
        function checkAllInputs() {
            let allFilled = true;
            inputs.forEach(input => {
                if (input.value.length === 0) {
                    allFilled = false;
                }
            });
            button.disabled = !allFilled;
        }

        // Handle form submission
        document.getElementById('otp-form').addEventListener('submit', (e) => {
            e.preventDefault();
            let otp = '';
            inputs.forEach(input => otp += input.value);

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

            fetch('{% url "account:otp_verify" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrfToken
                },
                body: JSON.stringify({ otp: otp })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert("OTP verified successfully!");
                    window.location.href = '{% url "core:dashboard" %}';
                } else {
                    alert(data.error || "Invalid or expired OTP.");
                    if (data.error == "User session not found"  || data.error == "Invalid or expired OTP"){
                        window.location.href = '{% url "account:login" %}';
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });
    </script>
</body>

</html>
