"""Preview component for Streamlit UI.

This component handles:
- Chart preview rendering
- Auto-update on state changes
- Preview in collapsible expander
"""

from __future__ import annotations

import streamlit as st

from plottini.core.plotter import Plotter
from plottini.ui.state import AppState


def generate_figure(state: AppState) -> None:
    """Generate the preview figure and store in state.

    This should be called early in the render cycle to ensure
    the figure is available for both preview and export.

    Args:
        state: Application state
    """
    if not state.can_render():
        state.current_figure = None
        return

    # Get dataframes in order
    dataframes = state.get_dataframes_list()

    if not dataframes:
        state.current_figure = None
        return

    try:
        # Create plotter
        plotter = Plotter(state.plot_config)

        # Create figure
        fig = plotter.create_figure(dataframes, state.series)

        # Store for export
        state.current_figure = fig
        state.clear_error()

    except Exception as e:
        state.current_figure = None
        state.set_error(f"Failed to generate figure: {e}")


def render_preview(state: AppState) -> None:
    """Render the chart preview in an expander.

    Args:
        state: Application state
    """
    with st.expander("Preview", expanded=True):
        if not state.can_render():
            st.info("Upload data and configure series to see preview.")
            return

        # Display the figure (already generated by generate_figure)
        if state.current_figure is not None:
            st.pyplot(state.current_figure, width="stretch")
        else:
            st.warning("Unable to generate preview.")


@st.fragment
def render_preview_column(state: AppState) -> None:
    """Render preview in right column layout.

    This function is a Streamlit fragment that can rerun independently,
    ensuring the preview stays in sync with config changes.

    Args:
        state: Application state
    """
    st.subheader("Preview")

    if not state.can_render():
        st.info("Upload data and configure at least one series.")
        return

    # Generate figure fresh within the fragment
    # This ensures we use the latest config values
    generate_figure(state)

    # Display the figure
    if state.current_figure is not None:
        st.pyplot(state.current_figure, width="stretch")
    else:
        st.warning("Unable to generate preview.")


__all__ = ["generate_figure", "render_preview", "render_preview_column"]
