from browser import document, ajax, console, window

console.log("Brython script is running")

def on_complete(req):
    console.log("Request completed with status", req.status)
    console.log("Response text:", req.text)
    try:
        data = window.JSON.parse(req.text)
        if req.status == 200 or req.status == 201:
            if req.status == 200 and 'redirect_url' in data:
                window.location.href = data['redirect_url']
            else:
                window.alert(data['message'])
            if req.status == 201 and "sign up" in data['message'].lower():
                window.setTimeout(lambda: window.location.replace("/"), 3000)  # Redirect after 3 seconds
            elif "password" in data['message'].lower():
                window.setTimeout(lambda: window.location.replace("/"), 3000)  # Redirect after 3 seconds
        else:
            window.alert(f"Request failed: {req.status} - {data['message']}")
            if document["signup-button"].disabled:
                document["signup-button"].disabled = False  # Re-enable the signup button on failure
                document["signup-button"].style.opacity = "1.0"  # Reset button opacity
                document["signup-message"].style.display = "none"  # Hide the message
            if document["forgot-password-button"].disabled:
                document["forgot-password-button"].disabled = False  # Re-enable the forgot password button on failure
                document["forgot-password-button"].style.opacity = "1.0"  # Reset button opacity
                document["forgot-password-message"].style.display = "none"  # Hide the message
    except:
        window.alert(f"Request failed: {req.status} - {req.text}")
        if document["signup-button"].disabled:
            document["signup-button"].disabled = False  # Re-enable the signup button on failure
            document["signup-button"].style.opacity = "1.0"  # Reset button opacity
            document["signup-message"].style.display = "none"  # Hide the message
        if document["forgot-password-button"].disabled:
            document["forgot-password-button"].disabled = False  # Re-enable the forgot password button on failure
            document["forgot-password-button"].style.opacity = "1.0"  # Reset button opacity
            document["forgot-password-message"].style.display = "none"  # Hide the message

def send_request(url, data, success_message):
    console.log("Sending request to", url, "with data", data)
    ajax.post(
        url,
        data=window.JSON.stringify(data),
        headers={'Content-Type': 'application/json'},
        oncomplete=on_complete
    )

def send_login_request(event):
    event.preventDefault()  # Prevent the default form submission
    console.log("Login form submitted")
    email = document["email"].value
    password = document["password"].value
    data = {"email": email, "password": password}
    send_request("/api/login", data, "Login successful!")

def send_signup_request(event):
    event.preventDefault()  # Prevent the default form submission
    console.log("Signup form submitted")
    email = document["signup_email"].value
    password = document["signup_password"].value
    data = {"email": email, "password": password}
    document["signup-button"].disabled = True  # Disable the signup button
    document["signup-button"].style.opacity = "0.5"  # Gray out the button
    document["signup-message"].style.display = "block"  # Show the message
    send_request("/api/signup", data, "Sign up successful! Please check your email to confirm your account.")

def send_forgot_password_request(event):
    event.preventDefault()  # Prevent the default form submission
    console.log("Forgot password form submitted")
    email = document["forgot_email"].value
    data = {"email": email}
    document["forgot-password-button"].disabled = True  # Disable the forgot password button
    document["forgot-password-button"].style.opacity = "0.5"  # Gray out the button
    document["forgot-password-message"].style.display = "block"  # Show the message
    send_request("/api/forgot_password", data, "If that email address exists in our system, a reset link has been sent!")

def send_reset_password_request(event):
    event.preventDefault()  # Prevent the default form submission
    console.log("Reset password form submitted")
    password = document["new_password"].value
    token = window.location.search.split('=')[1]
    data = {"password": password, "token": token}
    document["reset-password-button"].disabled = True  # Disable the reset password button
    document["reset-password-button"].style.opacity = "0.5"  # Gray out the button
    document["reset-password-message"].style.display = "block"  # Show the message
    send_request("/api/reset_password", data, "Password has been reset successfully!")

# Attach event handlers directly
console.log("Attaching event handlers")
if document.getElementById("login-form"):
    document.getElementById("login-form").bind("submit", send_login_request)
    console.log("Login form handler attached")
if document.getElementById("signup-form"):
    document.getElementById("signup-form").bind("submit", send_signup_request)
    console.log("Signup form handler attached")
if document.getElementById("forgot-password-form"):
    document.getElementById("forgot-password-form").bind("submit", send_forgot_password_request)
    console.log("Forgot password form handler attached")
if document.getElementById("reset-password-form"):
    document.getElementById("reset-password-form").bind("submit", send_reset_password_request)
    console.log("Reset password form handler attached")
