from __future__ import annotations

import pandas as pd
import streamlit as st


def render_training_panel(show_past_behavior: bool, example_trades: pd.DataFrame, alert_key: str) -> pd.Series | None:
    selected_trade: pd.Series | None = None
    if not show_past_behavior:
        return selected_trade

    st.subheader("Past Behavior Examples (Training)")
    if example_trades.empty:
        st.info("No closed example trades yet. Expand the period/timeframe to include more trend reversals.")
        return selected_trade

    wins = int((example_trades["outcome"] == "Win").sum())
    losses = int((example_trades["outcome"] == "Loss").sum())
    total_examples = int(len(example_trades))
    win_rate = round((wins / total_examples) * 100.0, 2) if total_examples else 0.0
    avg_pnl = round(float(example_trades["pnl_pct"].mean()), 2)

    t1, t2, t3, t4 = st.columns(4)
    t1.metric("Closed Examples", total_examples)
    t2.metric("Wins / Losses", f"{wins} / {losses}")
    t3.metric("Example Win Rate", f"{win_rate}%")
    t4.metric("Avg P/L per Example", f"{avg_pnl}%")

    latest_example = example_trades.iloc[-1]
    st.caption(
        "Latest closed example: "
        f"{latest_example['direction']} from {latest_example['entry_timestamp']} "
        f"to {latest_example['exit_timestamp']} "
        f"({latest_example['bars_held']} bars, {latest_example['pnl_pct']}%)."
    )
    st.caption("Click a row below to highlight that specific example on the chart.")
    st.caption("Example method: enter on trend confirmation bar close and exit on opposite trend confirmation.")

    display_examples_raw = example_trades.iloc[::-1].reset_index(drop=True)
    display_examples = display_examples_raw.copy()
    display_examples["entry_timestamp"] = display_examples["entry_timestamp"].astype(str)
    display_examples["exit_timestamp"] = display_examples["exit_timestamp"].astype(str)

    table_event = st.dataframe(
        display_examples,
        use_container_width=True,
        on_select="rerun",
        selection_mode="single-row",
        key=f"training-examples-{alert_key}",
    )
    selected_rows: list[int] = []
    try:
        selected_rows = list(table_event.selection.rows)
    except Exception:
        selected_rows = []

    selected_row_state_key = f"selected-training-row-{alert_key}"
    if selected_rows:
        selected_row_idx = int(selected_rows[0])
        st.session_state[selected_row_state_key] = selected_row_idx
    else:
        selected_row_idx = int(st.session_state.get(selected_row_state_key, 0))

    if selected_row_idx < 0 or selected_row_idx >= len(display_examples_raw):
        selected_row_idx = 0

    selected_trade = display_examples_raw.iloc[selected_row_idx]
    direction = str(selected_trade["direction"])
    entry_ts = str(selected_trade["entry_timestamp"])
    exit_ts = str(selected_trade["exit_timestamp"])
    entry_price = float(selected_trade["entry_price"])
    exit_price = float(selected_trade["exit_price"])
    bars_held = int(selected_trade["bars_held"])
    pnl_pct = float(selected_trade["pnl_pct"])
    outcome = str(selected_trade["outcome"])

    pnl_text = f"+{pnl_pct}%" if pnl_pct > 0 else f"{pnl_pct}%"
    result_text = "profit" if pnl_pct > 0 else ("loss" if pnl_pct < 0 else "flat result")
    st.info(
        f"Selected example explained: {direction} entry at {entry_ts} ({entry_price}), "
        f"exit at {exit_ts} ({exit_price}), held {bars_held} bars, {result_text} {pnl_text}, outcome: {outcome}."
    )
    return selected_trade
