from __future__ import annotations

from jarvis_finance.crypto.wallets import create_wallet, update_wallet, VALID_WALLET_TYPES
from jarvis_finance.dashboard.components.tables import show_table
from jarvis_finance.dashboard import data
from jarvis_finance.dashboard.actions import edit_mode_enabled, read_only_hint

PAGE_TITLE = "Wallets"


def _session_set(st, key: str, value) -> None:
    try:
        st.session_state[key] = value
    except Exception:
        pass


def render(st, conn) -> None:
    st.title("Wallets")
    st.caption("Kompakte Übersicht über Crypto-Wallets. Keine technischen IDs, keine Importnotizen.")
    cards = data.get_wallet_overview_cards(conn)
    wallet_rows = data.get_wallet_user_overview(conn)
    largest = max(wallet_rows, key=lambda r: data.d(r["_numeric_value_chf"]), default={"wallet_name": "—"})
    c1, c2, c3, c4 = st.columns(4)
    c1.metric("Gesamtwert Wallets", data.chf_text(cards["total_value_chf"]))
    c2.metric("Anzahl Wallets", cards["wallet_count"])
    c3.metric("Grösstes Wallet", largest["wallet_name"])
    c4.metric("Fehlende Verifikationen", cards["wallets_missing_verification"])

    st.subheader("Wallets")
    if not wallet_rows:
        st.info("Keine Wallets vorhanden.")
        return
    labels = [f"{r['wallet_name']} — {r['total_value_chf']}" for r in wallet_rows]
    selected = st.selectbox("Wallet auswählen", labels)
    selected_row = wallet_rows[labels.index(selected)] if selected in labels else wallet_rows[0]
    _session_set(st, "selected_crypto_wallet_id", selected_row["_wallet_id"])
    show_table(st, [{k: r[k] for k in ["wallet_name", "wallet_type", "total_value_chf", "coin_count", "status"]} for r in wallet_rows])

    st.subheader("Wallet Detail")
    detail = data.get_wallet_detail(conn, selected_row["_wallet_id"])
    d1, d2, d3, d4 = st.columns(4)
    d1.metric("Wallet", detail["wallet_name"])
    d2.metric("Typ", detail["typ"])
    d3.metric("Gesamtwert", detail["gesamtwert_chf"])
    d4.metric("Status", detail["status"])
    if detail.get("letzte_verifikation"):
        st.caption(f"Letzte Verifikation: {detail['letzte_verifikation']}")
    st.markdown("**Coins in diesem Wallet**")
    show_table(st, [{k: row[k] for k in data.visible_user_columns(row) if k not in {"actions"}} for row in detail["coins"]])

    st.markdown("**Aktionen**")
    if not edit_mode_enabled(st):
        read_only_hint(st)
    cols = st.columns(len(detail["actions"]))
    for col, action in zip(cols, detail["actions"]):
        col.button(action, key=f"wallet_action_{action}", disabled=True, help="Wallet-Schreibflows sind im User Mode bewusst deaktiviert; bitte später im Admin/Debug-Workflow nutzen.")

    with st.expander("Neues Wallet / Wallet bearbeiten"):
        if not edit_mode_enabled(st):
            read_only_hint(st)
        name = st.text_input("Wallet-Name")
        wallet_type = st.selectbox("Wallet-Typ", sorted(VALID_WALLET_TYPES))
        provider = st.text_input("Provider optional")
        chain = st.text_input("Chain/Network optional")
        note = st.text_area("Notiz optional")
        active = st.checkbox("Aktiv", value=True)
        confirm = st.checkbox("Review bestätigt")
        if st.button("Wallet speichern", disabled=not edit_mode_enabled(st)):
            try:
                if not confirm:
                    raise ValueError("Review-Bestätigung fehlt")
                wallet_id = create_wallet(conn, wallet_name=name, wallet_type=wallet_type, platform_provider=provider or None, network_chain=chain or None, notes=note or None)
                if not active:
                    update_wallet(conn, wallet_id, is_active=0)
                st.success("Wallet auditiert gespeichert.")
            except Exception as exc:
                st.error(str(exc))
