"""Login and registration pages."""

import streamlit as st

from frontend.api_client import login, register


def show_auth_page():
    st.title("MixLift")
    st.subheader("Marketing Mix Modeling made simple")

    tab1, tab2 = st.tabs(["Login", "Register"])

    with tab1:
        with st.form("login_form"):
            email = st.text_input("Email")
            password = st.text_input("Password", type="password")
            submitted = st.form_submit_button("Login")

            if submitted:
                if not email or not password:
                    st.error("Please fill in all fields")
                else:
                    result = login(email, password)
                    if result:
                        st.session_state["access_token"] = result["access_token"]
                        st.session_state["refresh_token"] = result["refresh_token"]
                        st.rerun()
                    else:
                        st.error("Invalid email or password")

    with tab2:
        with st.form("register_form"):
            name = st.text_input("Name (optional)")
            email = st.text_input("Email", key="reg_email")
            password = st.text_input("Password", type="password", key="reg_password")
            submitted = st.form_submit_button("Create Account")

            if submitted:
                if not email or not password:
                    st.error("Please fill in email and password")
                else:
                    result = register(email, password, name or None)
                    if result:
                        st.session_state["access_token"] = result["access_token"]
                        st.session_state["refresh_token"] = result["refresh_token"]
                        st.rerun()
                    else:
                        st.error("Registration failed. Email may already be in use.")
