import streamlit as st

from utils.db import (
    get_participation,
    get_votes,
    list_candidates,
    list_districts,
    list_stations,
    save_station_result,
)
from utils.ui import hero

district_id = st.session_state.get("district_id")
districts = {d["id"]: d["name"] for d in list_districts()}

hero(
    ":material/edit_note:",
    "إدخال النتائج",
    subtitle=f"الدائرة الحالية: {districts[district_id]}" if district_id else None,
)

if not district_id:
    st.info("أضف دائرة انتخابية أولاً.")
    st.stop()

candidates = list_candidates(district_id)
stations = list_stations(district_id)

if not candidates:
    st.warning("أضف مترشحين لهذه الدائرة من صفحة \"المترشحون واللوائح\" قبل إدخال النتائج.")
    st.stop()

if not stations:
    st.warning("أضف مكتب تصويت واحدا على الأقل من صفحة \"مراكز ومكاتب التصويت\" قبل إدخال النتائج.")
    st.stop()

communes = sorted({s["commune"] for s in stations}, key=lambda c: c or "")

c1, c2 = st.columns(2)
commune_choice = c1.selectbox(
    "اختر الجماعة",
    options=communes,
    format_func=lambda c: c or "بدون جماعة",
)

commune_stations = [s for s in stations if s["commune"] == commune_choice]
commune_stations.sort(key=lambda s: (s["name"].isdigit() is False, int(s["name"]) if s["name"].isdigit() else s["name"]))

stations_by_id = {s["id"]: s for s in commune_stations}
station_options = {
    s["id"]: s["name"] + (f" — {s['institution']}" if s["institution"] else "")
    for s in commune_stations
}
station_id = c2.selectbox(
    "اختر مكتب التصويت",
    options=list(station_options.keys()),
    format_func=lambda i: station_options[i],
)

station = stations_by_id[station_id]
existing_p = get_participation(station_id)
existing_votes = get_votes(station_id)

if existing_p:
    st.badge("تم إدخال نتائج هذا المكتب سابقًا", icon=":material/check_circle:", color="green")
else:
    st.badge("لم يتم إدخال نتائج هذا المكتب بعد", icon=":material/schedule:", color="orange")

with st.form("entry_form"):
    with st.container(border=True):
        st.subheader(":material/how_to_reg: المشاركة")
        c1, c2, c3 = st.columns(3)
        registered = c1.number_input(
            "عدد الناخبين المسجلين", min_value=0, step=1,
            value=existing_p["registered"] if existing_p else station["official_registered"],
        )
        voters = c2.number_input(
            "عدد المصوتين", min_value=0, step=1,
            value=existing_p["voters"] if existing_p else 0,
        )
        null_votes = c3.number_input(
            "الأوراق الملغاة", min_value=0, step=1,
            value=existing_p["null_votes"] if existing_p else 0,
        )
        blank = 0

    with st.container(border=True):
        st.subheader(":material/how_to_vote: الأصوات حسب المترشح / اللائحة")
        vote_inputs = {}
        for cand in candidates:
            label = f"{cand['name']} ({cand['party']})" if cand["party"] else cand["name"]
            vote_inputs[cand["id"]] = st.number_input(
                label, min_value=0, step=1,
                value=existing_votes.get(cand["id"], 0),
                key=f"vote_{station_id}_{cand['id']}",
            )

    submitted = st.form_submit_button(":material/save: حفظ النتائج", type="primary")

    if submitted:
        valid_votes = sum(vote_inputs.values())  # عدد الأصوات الصحيحة = مجموع الأصوات الموزعة على المترشحين
        errors = []

        if voters > registered:
            errors.append(
                f"عدد المصوتين ({voters}) أكبر من عدد الناخبين المسجلين ({registered})."
            )
        if valid_votes != voters:
            errors.append(
                f"عدد الأصوات الصحيحة ({valid_votes}) لا يساوي عدد المصوتين ({voters})."
            )

        if errors:
            st.error(
                "**لم يتم الحفظ — يوجد خطأ فالحساب، صحح الأرقام أولاً:**\n\n"
                + "\n\n".join(f"- {e}" for e in errors),
                icon=":material/error:",
            )
        else:
            save_station_result(station_id, registered, voters, blank, null_votes, vote_inputs)
            st.toast("تم حفظ النتائج بنجاح", icon=":material/check_circle:")
            st.rerun()

if existing_p and existing_p["updated_at"]:
    st.caption(f"آخر تحديث: {existing_p['updated_at']}")
