import json
from pathlib import Path
from typing import Literal

import streamlit as st

LANGUAGES = ["EN", "CZ"]


@st.cache_data
def get_translations() -> dict[
    Literal["CZ", "EN"],
    dict[Literal["main_page", "sidebar", "add_step", "login_page"], dict[str, str]],
]:
    with (Path(__file__).parent.parent.parent / "config/lang.json").open() as f:
        return json.loads(f.read())


def get_sidebar(is_login: bool = False) -> None:
    index, translation = (
        (1, st.session_state.translations["CZ"])
        if ("language" in st.session_state and st.session_state.language == "CZ")
        else (0, st.session_state.translations["EN"])
    )
    with st.sidebar:
        if not is_login:
            st.markdown(f"#### {translation['sidebar']['user']}")
            st.text("E-mail:              " + str(st.user.email))
            st.text(f"{translation['sidebar']['name']}:               " + str(st.user.name))
            st.button(translation["sidebar"]["logout"], on_click=st.logout)
            st.divider()

        st.session_state["language"] = st.radio(
            translation["sidebar"]["language"],
            options=LANGUAGES,
            index=index,
            key="language_widget",
        )
        if index != LANGUAGES.index(st.session_state.language):
            st.rerun()


def validate_step_input() -> bool:
    errors: list[str] = []
    if not st.session_state.title_en or not st.session_state.title_cz:
        errors.append("Please enter a title")
    if not st.session_state.previous:
        errors.append("Please select a previous step")
    if st.session_state.type == "Text" and (not st.session_state.text_en or not st.session_state.text_cz):
        errors.append("Please enter a text")
    if st.session_state.type == "Link" and not st.session_state.link:
        errors.append("Please enter a link")

    for error in errors:
        st.toast(error)
    return len(errors) == 0
