"""
数据分析视图 - 数据概览、表格浏览、可视化分析
"""

import streamlit as st
import pandas as pd

from super_datascope.components.json_table import JsonDataTable
from super_datascope.components.data_insight import (
    render_quick_analysis,
    render_basic_statistics,
    InteractiveChartBuilder,
)


def data_analysis_view():
    """数据分析视图页面"""

    if 'data' not in st.session_state or st.session_state.data is None:
        st.warning("请先选择并加载数据文件")
        return

    df = st.session_state.data
    config = st.session_state.get('current_config', {})

    # 数据概览
    st.subheader("📈 数据概览")

    col1, col2, col3, col4 = st.columns(4)
    with col1:
        st.metric("总记录数", len(df))
    with col2:
        st.metric("总列数", len(df.columns))
    with col3:
        memory_mb = df.memory_usage(deep=True).sum() / (1024 * 1024)
        st.metric("内存占用", f"{memory_mb:.1f} MB")
    with col4:
        # 显示数据类型分布
        n_numeric = len(df.select_dtypes(include=['number']).columns)
        n_other = len(df.columns) - n_numeric
        st.metric("数值/其他列", f"{n_numeric}/{n_other}")

    # 数据表格
    st.subheader("📋 数据表格")
    json_table = JsonDataTable(df, config, name="data_overview", show_index=True)
    json_table.display(page_size=20, height=600)

    # 数据可视化
    st.subheader("📊 数据可视化")

    tab1, tab2, tab3 = st.tabs(["📈 快速分析", "🎯 高级分析", "📋 基础统计"])

    with tab1:
        render_quick_analysis(df, key_prefix="data_analysis")

    with tab2:
        chart_builder = InteractiveChartBuilder(df, "data_analysis")
        chart_builder.render()

    with tab3:
        render_basic_statistics(df)
