import streamlit as st

from app_pages import candidates, dashboard, stations
from utils.db import list_districts
from utils.ui import hero

if not st.session_state.get("admin_authenticated"):
    _, center, _ = st.columns([1, 1.4, 1])
    with center:
        st.space("large")
        st.title(":material/lock: لوحة الإدارة", text_alignment="center")
        st.caption("هاد الفضاء مخصص للمسؤولين فقط", text_alignment="center")
        with st.container(border=True):
            with st.form("admin_login_form"):
                password = st.text_input("كلمة السر", type="password")
                submitted = st.form_submit_button(
                    "دخول", icon=":material/login:", type="primary", width="stretch"
                )
                if submitted:
                    if password == st.secrets.get("admin_password"):
                        st.session_state.admin_authenticated = True
                        st.rerun()
                    else:
                        st.error("كلمة السر غير صحيحة.")
    st.stop()

hero(":material/admin_panel_settings:", "لوحة الإدارة")

with st.sidebar:
    if st.button("تسجيل الخروج", icon=":material/logout:"):
        st.session_state.admin_authenticated = False
        st.rerun()

districts = list_districts()
if districts:
    options = {d["id"]: d["name"] for d in districts}
    current = st.session_state.get("district_id")
    selected = st.selectbox(
        "الدائرة الانتخابية",
        options=list(options.keys()),
        format_func=lambda i: options[i],
        index=list(options.keys()).index(current) if current in options else 0,
        key="admin_district_select",
    )
    st.session_state.district_id = selected

tab_dashboard, tab_candidates, tab_stations = st.tabs(
    ["لوحة النتائج", "المترشحون واللوائح", "مراكز ومكاتب التصويت"]
)

with tab_dashboard:
    dashboard.render()

with tab_candidates:
    candidates.render()

with tab_stations:
    stations.render()
