# === Ajout de produit personnalisé ===
import networkx as nx
import streamlit as st

from utils.persistance import get_champ_statut, maj_champ_statut, supprime_champ_statut
from utils.translations import _


def ajouter_produit(G: nx.DiGraph) -> nx.DiGraph:
    """Affiche l'interface d'ajout d'un nouveau produit personnalise au graphe."""
    st.markdown(f"## {str(_('pages.personnalisation.add_new_product'))}")

    # Restauration des produits personnalisés sauvegardés
    if "pages.personnalisation.create_product.fait" not in st.session_state and get_champ_statut("pages.personnalisation.create_product.fait") == "oui":
        index = 0
        while True:
            new_prod = get_champ_statut(f"pages.personnalisation.create_product.{index}.nom")
            if new_prod == "":
                break

            G.add_node(new_prod, niveau="0", personnalisation="oui", label=new_prod)

            sel_new_op = get_champ_statut(f"pages.personnalisation.create_product.{index}.edge")
            if sel_new_op:
                G.add_edge(new_prod, sel_new_op)

            i = 0
            while True:
                comp = get_champ_statut(f"pages.personnalisation.create_product.{index}.composants.{i}")
                if comp == "":
                    break
                G.add_edge(new_prod, comp)
                i += 1

            index += 1

    niveau1 = sorted([n for n, d in G.nodes(data=True) if d.get("niveau") == "1"])
    ops_dispo = sorted([n for n, d in G.nodes(data=True) if d.get("niveau") == "assemblage"])

    if "pages.personnalisation.add.new_product_name" not in st.session_state:
        st.session_state["pages.personnalisation.add.new_product_name"] = get_champ_statut("pages.personnalisation.add.new_product_name")

    new_prod = st.text_input(
        str(_("pages.personnalisation.new_product_name")),
        key="pages.personnalisation.add.new_product_name"
    )

    if new_prod:
        if new_prod in G.nodes:
            st.warning(str(_("pages.personnalisation.product_exists")))
            return G

        if "pages.personnalisation.add.assembly_operation" not in st.session_state:
            st.session_state["pages.personnalisation.add.assembly_operation"] = get_champ_statut("pages.personnalisation.add.assembly_operation")

        if "pages.personnalisation.add.components_to_link" not in st.session_state:
            composants = []
            i = 0
            while True:
                val = get_champ_statut(f"pages.personnalisation.add.components_to_link.{i}")
                if val == "":
                    break
                composants.append(val)
                i += 1
            st.session_state["pages.personnalisation.add.components_to_link"] = composants

        ops_dispo = sorted([
            n for n, d in G.nodes(data=True)
            if d.get("niveau") == "10"
            and any(G.has_edge(p, n) and G.nodes[p].get("niveau") == "0" for p in G.predecessors(n))
        ])
        sel_new_op = st.selectbox(str(_("pages.personnalisation.assembly_operation")), ops_dispo,
            key="pages.personnalisation.add.assembly_operation")

        sel_comps = st.multiselect(
            str(_("pages.personnalisation.components_to_link")),
            options=niveau1,
            key="pages.personnalisation.add.components_to_link"
        )

        if st.button(str(_("pages.personnalisation.create_product"))):
            G.add_node(new_prod, niveau="0", personnalisation="oui", label=new_prod)

            # Trouver le prochain index disponible
            index = 0
            while get_champ_statut(f"pages.personnalisation.create_product.{index}.nom") != "":
                index += 1

            maj_champ_statut(f"pages.personnalisation.create_product.{index}.nom", new_prod)

            if sel_new_op != str(_("pages.personnalisation.none")):
                G.add_edge(new_prod, sel_new_op)
                maj_champ_statut(f"pages.personnalisation.create_product.{index}.edge", sel_new_op)

            for j, comp in enumerate(sel_comps):
                G.add_edge(new_prod, comp)
                maj_champ_statut(f"pages.personnalisation.create_product.{index}.composants.{j}", comp)

            maj_champ_statut("pages.personnalisation.create_product.fait", "oui")

            # Nettoyage de session et des champs persistants
            del st.session_state["pages.personnalisation.add.new_product_name"]
            del st.session_state["pages.personnalisation.add.assembly_operation"]
            del st.session_state["pages.personnalisation.add.components_to_link"]
            supprime_champ_statut("pages.personnalisation.add")

            st.success(f"{new_prod} {str(_('pages.personnalisation.added'))}")
            st.rerun()

    return G
