"""Experiment overview and sidebar sections."""

import pandas as pd
import streamlit as st

from entropice.dashboard.utils.loaders import TrainingResult, get_available_experiments


def render_experiment_sidebar() -> str | None:
    """Render sidebar for experiment selection.

    Returns:
        Selected experiment name or None

    """
    st.sidebar.header("🔬 Experiment Selection")

    experiments = get_available_experiments()

    if not experiments:
        st.sidebar.warning("No experiments found. Create an experiment directory with training results first.")
        return None

    selected_experiment = st.sidebar.selectbox(
        "Select Experiment",
        options=experiments,
        index=0,
        help="Choose an experiment to analyze",
    )

    return selected_experiment


def render_experiment_overview(
    experiment_name: str,
    training_results: list[TrainingResult],
    summary_df: pd.DataFrame,
):
    """Render experiment overview section.

    Args:
        experiment_name: Name of the experiment
        training_results: List of RandomSearchCV training results
        summary_df: Summary DataFrame with all results

    """
    st.header(f"📊 Experiment: {experiment_name}")

    # Show summary statistics
    col1, col2, col3, col4 = st.columns(4)

    with col1:
        st.metric("Total Training Runs", len(training_results))

    with col2:
        hpsearch_runs = [tr for tr in training_results if tr.run.method_type == "HPOCV"]
        st.metric("RandomSearchCV Runs", len(hpsearch_runs))

    with col3:
        autogluon_runs = [tr for tr in training_results if tr.run.method_type == "AutoML"]
        st.metric("AutoGluon Runs", len(autogluon_runs))

    with col4:
        unique_configs = summary_df[["grid", "level", "task", "target"]].drop_duplicates()
        st.metric("Unique Configurations", len(unique_configs))

    st.divider()

    # Show summary table
    st.subheader("Experiment Summary")

    display_columns = [
        "method",
        "task",
        "target",
        "model",
        "grid_level",
        "test_score",
        "best_metric",
        "n_trials",
    ]
    available_columns = [col for col in display_columns if col in summary_df.columns]

    st.dataframe(
        summary_df[available_columns].sort_values("test_score", ascending=False),
        width="stretch",
        hide_index=True,
    )
