from __future__ import annotations

from typing import Any

import streamlit as st

from web_core.auth.profile_store import (
    create_profile,
    find_existing_profile_id,
    first_query_param_value,
    is_truthy_flag,
    list_web_profiles,
    mark_profile_login,
    normalize_pin,
    normalize_profile_id,
    profile_exists,
    profile_requires_pin,
    verify_profile_pin,
)


def render_profile_login(now_epoch: float, query_params: Any, session_expired: bool) -> None:
    existing_profiles = set(list_web_profiles())
    st.subheader("Profile Login")
    st.info("Login with an existing profile or create a new one. Settings are isolated per profile.")
    if session_expired:
        st.warning("Your profile session timed out due to inactivity. Please log in again.")

    initial_profile = first_query_param_value(query_params, "profile") or ""
    remember_default = is_truthy_flag(first_query_param_value(query_params, "remember"))
    login_profile = st.text_input("Login profile name", value=initial_profile, placeholder="e.g. matt")
    login_pin = st.text_input("PIN (if enabled)", value="", type="password", max_chars=6)
    remember_me = st.checkbox("Remember me on this browser", value=remember_default or True)
    if st.button("Login", type="primary", use_container_width=True):
        selected_match = find_existing_profile_id(login_profile, existing_profiles)
        if selected_match is None:
            st.error("Profile not found. Enter the exact profile name or create a new one below.")
        elif profile_requires_pin(selected_match) and not verify_profile_pin(selected_match, login_pin):
            st.error("Incorrect PIN.")
        else:
            mark_profile_login(selected_match, now_epoch=int(now_epoch))
            st.session_state["active_profile"] = selected_match
            st.session_state["profile_last_active_at"] = now_epoch
            query_params["profile"] = selected_match
            if remember_me:
                query_params["remember"] = "1"
            elif "remember" in query_params:
                del query_params["remember"]
            st.rerun()

    st.divider()
    create_profile_name = st.text_input("Create profile name", value="", placeholder="e.g. sara")
    create_pin = st.text_input("Set PIN (optional, 4-6 digits)", value="", type="password", max_chars=6)
    if st.button("Create Profile", use_container_width=True):
        selected = normalize_profile_id(create_profile_name)
        if profile_exists(selected, existing_profiles):
            st.error("That profile already exists (including case-insensitive matches). Use Login instead.")
        elif create_pin and normalize_pin(create_pin) is None:
            st.error("PIN must be 4-6 digits.")
        else:
            create_profile(selected, pin=create_pin or None, now_epoch=int(now_epoch))
            st.session_state["active_profile"] = selected
            st.session_state["profile_last_active_at"] = now_epoch
            query_params["profile"] = selected
            if remember_me:
                query_params["remember"] = "1"
            elif "remember" in query_params:
                del query_params["remember"]
            st.rerun()
