import os
import time
from src.markers import display_interventions, display_solved, show_requests, show_verified_requests
from src.filters import show_requests_filters, show_interventions_filters

import folium
import streamlit as st
from huggingface_hub import HfApi
from streamlit_folium import st_folium
from src.components import show_dataframes_metrics, show_embed_code, show_donations
from src.text_content import (
    CREDITS_TEXT,
    LOGO,
    SLOGAN,
)
from src.utils import init_map
from src.map_utils import get_legend_macro
from src.dataframes import load_data
import gettext

gettext.install("myapplication")

TOKEN = os.environ.get("HF_TOKEN", None)

api = HfApi(TOKEN)


# Initialize Streamlit Config
st.set_page_config(
    layout="wide",
    initial_sidebar_state="collapsed",
    page_icon="🤝",
    page_title="Nt3awnou نتعاونو",
)

# Initialize States
if "sleep_time" not in st.session_state:
    st.session_state.sleep_time = 2
if "auto_refresh" not in st.session_state:
    st.session_state.auto_refresh = False

auto_refresh = st.sidebar.checkbox("Auto Refresh?", st.session_state.auto_refresh)
if auto_refresh:
    number = st.sidebar.number_input("Refresh rate in seconds", value=st.session_state.sleep_time)
    st.session_state.sleep_time = number

# Logo and Title
st.markdown(LOGO, unsafe_allow_html=True)
# st.title("Nt3awnou نتعاونو")
st.markdown(SLOGAN, unsafe_allow_html=True)

# Localization
lang_options = {
    "ar": "العربية",
    "fr": "Français",
    "en": "English",
}
# multiple option (NOT in sidebar)
lang = st.selectbox("Choose language / اختر اللغة", list(lang_options.keys()), format_func=lambda x: lang_options[x])

if lang == "en":
    _ = gettext.gettext
else:
    localizator = gettext.translation("messages", localedir="locales", languages=[lang])
    localizator.install()

# Initialize map
m, emergency_fgs, intervention_fgs = init_map()
fg = folium.FeatureGroup(name="Markers")

# Selection of requests
selected_options, options, show_unverified, show_interventions = show_requests_filters()

# Load data
(
    df,
    filtered_df,
    interventions_df,
    verified_df,
    filtered_verified_df,
    solved_verified_requests,
    douar_df,
    len_requests,
    len_interventions,
    len_solved_verified_requests,
) = load_data(show_unverified, selected_options, options)

# Selection of interventions
selected_statuses = show_interventions_filters()

# Add interventions markers to map
if show_interventions:
    display_solved(solved_verified_requests, selected_statuses, fg)
    display_interventions(interventions_df, selected_statuses, m, intervention_fgs)

# Add requests markers to map
if show_unverified:
    show_requests(filtered_df, fg)

# Add verified requests markers to map
show_verified_requests(filtered_verified_df, emergency_fgs)

# Add legend
legend_macro = get_legend_macro(show_unverified)
# delete old legend
for child in m.get_root()._children:
    pass  # TODO: fix this
    # if child.startswith("macro_element"):
    #     m.get_root()._children.remove(child)
m.get_root().add_child(legend_macro)
# add_village_names(douar_df, m)
st_folium(m, use_container_width=True, returned_objects=[], feature_group_to_add=fg, key="map")

# Embed code
show_embed_code()

# Show metrics
show_dataframes_metrics(len_requests, len_interventions, len_solved_verified_requests, lang)

# Verified Requests table
# st.divider()
# st.subheader(_("📝 **Table of verified requests**"))
# drop_cols = [
#     "Phone Number",
#     "id",
#     "Status",
#     "Intervenant ",
#     "Intervention Date",
#     "Any remarks",
#     "VerificationStatus",
#     "Automatic Extracted Coordinates",
# ]
# display_dataframe(
#     verified_df, drop_cols, VERIFIED_REQUESTS_URL, search_id=True, for_help_requests=True, show_link=False
# )

# Requests table
# st.divider()
# st.subheader("📝 **Table of requests**")
# drop_cols = [
#     "(عند الامكان) رقم هاتف شخص موجود في عين المكان",
#     "الرجاء الضغط على الرابط التالي لمعرفة موقعك إذا كان متاحا",
#     "GeoStamp",
#     "GeoCode",
#     "GeoAddress",
#     "Status",
#     "id",
# ]
# display_dataframe(filtered_df, drop_cols, REQUESTS_URL, search_id=True, for_help_requests=True)

# # Interventions table
# st.divider()
# st.subheader("📝 **Table of interventions**")
# display_dataframe(
#     interventions_df,
#     [],  # We show NGOs contact information
#     INTERVENTIONS_URL,
#     search_id=False,
#     status=True,
#     for_help_requests=False,
# )

# Submit an id for review
# st.divider()
# id_review_submission(api)


# Donations can be made to the gouvernmental fund under the name
st.divider()
show_donations(lang)

# Credits
st.markdown(
    CREDITS_TEXT,
    unsafe_allow_html=True,
)
if auto_refresh:
    time.sleep(number)
    st.experimental_rerun()

if lang == "ar":
    st.markdown(
        """
        <style>
        body {
            text-align: right;
        }
        </style>
        """,
        unsafe_allow_html=True,
    )