"""Storage Statistics Section for Entropice Dashboard."""

import pandas as pd
import plotly.graph_objects as go
import streamlit as st

from entropice.dashboard.utils.loaders import StorageInfo, load_storage_statistics
from entropice.utils.paths import DATA_DIR


def _format_bytes(bytes_value: int) -> str:
    """Format bytes into human-readable string."""
    value = float(bytes_value)
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if value < 1024.0:
            return f"{value:.2f} {unit}"
        value /= 1024.0
    return f"{value:.2f} PB"


def _create_storage_bar_chart(storage_infos: list[StorageInfo]) -> go.Figure:
    """Create a horizontal bar chart showing storage usage by subdirectory."""
    if not storage_infos:
        return go.Figure()

    # Prepare data
    names = [info.name for info in storage_infos]
    sizes = [info.size_bytes / (1024**3) for info in storage_infos]  # Convert to GB
    file_counts = [info.file_count for info in storage_infos]

    # Create figure
    fig = go.Figure()

    # Add bar trace
    fig.add_trace(
        go.Bar(
            y=names,
            x=sizes,
            orientation="h",
            text=[f"{s:.2f} GB" for s in sizes],
            textposition="auto",
            hovertemplate="<b>%{y}</b><br>Size: %{x:.2f} GB<br>Files: %{customdata:,}<extra></extra>",
            customdata=file_counts,
            marker={
                "color": sizes,
                "colorscale": "Blues",
                "showscale": False,
            },
        )
    )

    # Update layout
    fig.update_layout(
        title="Storage Usage by Subdirectory",
        xaxis_title="Size (GB)",
        yaxis_title="Directory",
        height=max(400, len(names) * 40),  # Dynamic height based on number of directories
        showlegend=False,
        margin={"l": 200, "r": 50, "t": 50, "b": 50},
    )

    return fig


def _create_storage_pie_chart(storage_infos: list[StorageInfo]) -> go.Figure:
    """Create a pie chart showing storage distribution."""
    if not storage_infos:
        return go.Figure()

    # Prepare data
    names = [info.name for info in storage_infos]
    sizes = [info.size_bytes for info in storage_infos]

    # Create figure
    fig = go.Figure(
        data=[
            go.Pie(
                labels=names,
                values=sizes,
                textinfo="label+percent",
                hovertemplate="<b>%{label}</b><br>Size: %{customdata}<br>%{percent}<extra></extra>",
                customdata=[info.display_size for info in storage_infos],
            )
        ]
    )

    # Update layout
    fig.update_layout(
        title="Storage Distribution",
        height=500,
    )

    return fig


def render_storage_statistics():
    """Render the storage statistics section showing disk usage for DATA_DIR subdirectories."""
    st.header("💾 Storage Statistics")

    st.markdown(
        f"""
        This section shows the disk usage of subdirectories in the data directory:
        **`{DATA_DIR}`**

        Data is collected using [dust](https://github.com/bootandy/dust), a modern disk usage analyzer.
        Statistics are cached for 5 minutes to reduce overhead.
        """
    )

    # Load storage statistics
    with st.spinner("Analyzing storage usage..."):
        storage_infos, total_size, total_files = load_storage_statistics()

    if not storage_infos:
        st.warning("No storage data available. The data directory may be empty or inaccessible.")
        return

    # Display summary metrics
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("Total Storage Used", _format_bytes(total_size))
    with col2:
        st.metric("Total Files", f"{total_files:,}")
    with col3:
        st.metric("Number of Subdirectories", len(storage_infos))

    # Create tabs for different visualizations
    tab1, tab2, tab3 = st.tabs(["📊 Bar Chart", "🥧 Pie Chart", "📋 Detailed Table"])

    with tab1:
        st.plotly_chart(_create_storage_bar_chart(storage_infos), use_container_width=True)

    with tab2:
        st.plotly_chart(_create_storage_pie_chart(storage_infos), use_container_width=True)

    with tab3:
        # Create DataFrame for detailed view
        df = pd.DataFrame(
            [
                {
                    "Directory": info.name,
                    "Size": info.display_size,
                    "Size (Bytes)": info.size_bytes,
                    "Files": info.file_count,
                    "Percentage": f"{(info.size_bytes / total_size * 100):.2f}%",
                }
                for info in storage_infos
            ]
        )

        st.dataframe(
            df[["Directory", "Size", "Files", "Percentage"]],
            use_container_width=True,
            hide_index=True,
        )

        # Add download button for detailed data
        st.download_button(
            label="📥 Download Storage Statistics (CSV)",
            data=df.to_csv(index=False),
            file_name="entropice_storage_statistics.csv",
            mime="text/csv",
        )
