import streamlit as st

from utils.db import (
    add_station,
    delete_station,
    delete_stations_by_commune,
    import_stations,
    list_communes,
    list_districts,
    list_stations_by_commune,
    rename_commune,
    update_station,
)
from utils.excel_import import parse_stations_workbook


def render():
    district_id = st.session_state.get("district_id")
    districts = {d["id"]: d["name"] for d in list_districts()}

    if not district_id:
        st.info("أضف دائرة انتخابية أولاً من صفحة المترشحين.")
        return

    st.caption(f"الدائرة الحالية: **{districts[district_id]}**")

    with st.container(border=True):
        st.subheader("إضافة مكتب تصويت")
        with st.form("add_station_form", clear_on_submit=True):
            col1, col2 = st.columns(2)
            new_commune = col1.text_input("الجماعة / المقاطعة")
            new_name = col2.text_input("اسم أو رقم مكتب التصويت")
            submitted = st.form_submit_button("إضافة", icon=":material/add:")
            if submitted:
                if new_name.strip():
                    add_station(district_id, new_commune, new_name)
                    st.toast(f"تمت إضافة {new_name}", icon=":material/check_circle:")
                    st.rerun()
                else:
                    st.warning("الرجاء إدخال اسم مكتب التصويت.")

    with st.container(border=True):
        st.subheader(":material/upload_file: استيراد من ملف Excel")
        st.caption(
            "يقبل صيغتين: ورقة \"مكاتب\" بأعمدة منفصلة، أو ورقة واحدة بعلامات "
            "\"جماعة:\" و\"مؤسسة:\" (مثل جماعة الشوافع والحدادة)."
        )
        uploaded = st.file_uploader("اختر ملف الجماعة (xlsx)", type=["xlsx"], key="stations_uploader")

        if uploaded is not None:
            commune_guess, rows, error = parse_stations_workbook(uploaded)
            if error:
                st.error(error)
            elif not rows:
                st.warning("لم يتم العثور على أي صف مكتب تصويت صالح في الملف.")
            else:
                st.success(f"تم العثور على {len(rows)} مكتب تصويت في الملف.")
                # Key includes the file identity so a newly uploaded file gets its own
                # fresh guess instead of reusing whatever commune name was typed for
                # the previous file (Streamlit ignores `value=` once a keyed widget
                # already has state).
                commune_name = st.text_input(
                    "اسم الجماعة (تحقق منها قبل الاستيراد)",
                    value=commune_guess,
                    key=f"import_commune_name_{uploaded.name}_{uploaded.size}",
                )
                st.dataframe(
                    rows,
                    hide_index=True,
                    width="stretch",
                    column_config={
                        "name": st.column_config.TextColumn("رقم المكتب"),
                        "institution": st.column_config.TextColumn("اسم المؤسسة"),
                        "official_registered": st.column_config.NumberColumn("عدد الناخبين"),
                    },
                )
                if st.button(":material/publish: تأكيد الاستيراد", type="primary", disabled=not commune_name.strip()):
                    added, updated = import_stations(district_id, commune_name, rows)
                    st.toast(
                        f"تم استيراد {added} مكتب جديد وتحديث {updated} مكتب موجود",
                        icon=":material/check_circle:",
                    )
                    st.rerun()

    st.divider()
    st.subheader(":material/tune: إدارة المكاتب")

    communes = list_communes(district_id)
    if not communes:
        st.info("لا توجد مكاتب تصويت بعد لهذه الدائرة.")
        return

    total_stations = sum(c["station_count"] for c in communes)
    commune_labels = {
        c["commune"]: f"{c['commune'] or 'بدون جماعة'} ({c['station_count']})" for c in communes
    }
    selected_commune = st.selectbox(
        "اختر الجماعة",
        options=list(commune_labels.keys()),
        format_func=lambda c: commune_labels[c],
    )

    st.caption(f"إجمالي المكاتب المسجلة في الدائرة: {total_stations}")

    with st.container(border=True):
        rc1, rc2 = st.columns([4, 1])
        renamed = rc1.text_input(
            "تعديل اسم الجماعة",
            value=selected_commune,
            key=f"rename_commune_{selected_commune}",
        )
        if rc2.button("حفظ الاسم", icon=":material/save:"):
            if renamed.strip() and renamed.strip() != selected_commune:
                rename_commune(district_id, selected_commune, renamed)
                st.toast("تم تعديل اسم الجماعة", icon=":material/check_circle:")
                st.rerun()

        if st.button(
            "حذف كل مكاتب هذه الجماعة",
            key=f"del_commune_{selected_commune}",
            icon=":material/delete_sweep:",
        ):
            delete_stations_by_commune(district_id, selected_commune)
            st.toast("تم حذف كل مكاتب الجماعة", icon=":material/check_circle:")
            st.rerun()

    stations = list_stations_by_commune(district_id, selected_commune)
    st.markdown(f"**مكاتب {selected_commune or 'بدون جماعة'}** ({len(stations)})")

    for s in stations:
        with st.container(border=True):
            c1, c2, c3, c4 = st.columns([2, 3, 2, 1])
            edited_name = c1.text_input(
                "رقم المكتب", value=s["name"], key=f"st_name_{s['id']}", label_visibility="collapsed"
            )
            edited_institution = c2.text_input(
                "اسم المؤسسة",
                value=s["institution"],
                key=f"st_inst_{s['id']}",
                label_visibility="collapsed",
            )
            edited_registered = c3.number_input(
                "عدد الناخبين",
                min_value=0,
                step=1,
                value=s["official_registered"],
                key=f"st_reg_{s['id']}",
                label_visibility="collapsed",
            )
            if (
                edited_name != s["name"]
                or edited_institution != s["institution"]
                or edited_registered != s["official_registered"]
            ):
                update_station(s["id"], selected_commune, edited_name, edited_institution, edited_registered)

            if c4.button("حذف", key=f"del_station_{s['id']}", icon=":material/delete:"):
                delete_station(s["id"])
                st.toast("تم حذف المكتب", icon=":material/check_circle:")
                st.rerun()


if __name__ == "__main__":
    render()
