import streamlit as st
from components.code_editor import render_code_editor
from components.dataset_explorer import render_dataset_explorer
from components.visualization import render_visualization
from components.model_metrics import render_model_metrics
import os
import sys
import time
from utils import load_css, create_logo

# Page configuration
st.set_page_config(
    page_title="Python & HuggingFace Explorer",
    page_icon="🤗",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Load custom CSS
load_css()

# Main content
def main():
    # Create sidebar
    with st.sidebar:
        create_logo()
        st.title("Navigation")
        page = st.radio(
            "Select a page:",
            ["Home", "Code Editor", "Dataset Explorer", "Visualizations", "Model Metrics"]
        )
        
        # HF Dataset search
        st.sidebar.markdown("---")
        st.sidebar.subheader("Dataset Quick Search")
        dataset_name = st.sidebar.text_input("Enter a HuggingFace dataset name")
        if dataset_name and st.sidebar.button("Load Dataset"):
            st.session_state.dataset_name = dataset_name
            if page != "Dataset Explorer":
                st.sidebar.info("Dataset loaded! Go to Dataset Explorer to view it.")
        
        st.sidebar.markdown("---")
        st.sidebar.markdown("""
        <div style="font-size: 0.8em; color: #666; text-align: center;">
            <p>Built with ❤️ using</p>
            <p>Streamlit & HuggingFace</p>
            <p style="font-size: 0.9em; margin-top: 5px;">© 2025 Python Explorer</p>
        </div>
        """, unsafe_allow_html=True)

    # Initialize session state for dataset
    if 'dataset_name' not in st.session_state:
        st.session_state.dataset_name = None
    
    if 'code_content' not in st.session_state:
        st.session_state.code_content = """# Sample Python code
from datasets import load_dataset
import pandas as pd
import matplotlib.pyplot as plt

# Load a dataset from Hugging Face
dataset = load_dataset("glue", "sst2", split="train")
df = pd.DataFrame(dataset)

# Display the first few rows
print(df.head())

# Simple analysis
print(f"Number of examples: {len(df)}")
print(f"Columns: {df.columns}")

# Visualize class distribution
plt.figure(figsize=(8, 5))
df['label'].value_counts().plot(kind='bar')
plt.title('Class Distribution')
plt.xlabel('Class')
plt.ylabel('Count')
plt.tight_layout()
plt.show()
"""
    
    # Page content
    if page == "Home":
        render_home()
    elif page == "Code Editor":
        render_code_editor()
    elif page == "Dataset Explorer":
        render_dataset_explorer()
    elif page == "Visualizations":
        render_visualization()
    elif page == "Model Metrics":
        render_model_metrics()

def render_home():
    # Display header image instead of using a title
    from PIL import Image
    import os
    
    # Path to the logo image in the center of the page
    center_logo_path = "assets/python_huggingface_logo.png"
    
    # Check if the logo exists and display it
    if os.path.exists(center_logo_path):
        center_col1, center_col2, center_col3 = st.columns([1, 2, 1])
        with center_col2:
            image = Image.open(center_logo_path)
            # Resize image to 25% of original dimensions
            width, height = image.size
            resized_image = image.resize((width//4, height//4))
            st.image(resized_image, use_container_width=True)
    else:
        st.title("Python & HuggingFace Explorer")
    
    # Introduction with improved styling
    st.markdown("""
    <div style="background-color: #FFFFFF; padding: 20px; border-radius: 10px; margin-bottom: 20px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
        <h2 style="color: #2196F3; text-align: center;">Welcome to the Explorer!</h2>
        <p style="font-size: 1.1em; line-height: 1.6;">This interactive platform brings together the power of Python and the HuggingFace ecosystem. 
        Write and execute code, explore datasets from the HuggingFace Hub, create beautiful visualizations, 
        and analyze model performance metrics - all in one seamless environment.</p>
    </div>
    """, unsafe_allow_html=True)
    
    # Feature cards
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("""
        <div style="background-color: #FFFFFF; padding: 20px; border-radius: 10px; height: 200px;">
            <h3 style="color: #2196F3;">💻 Code Editor</h3>
            <p>Write, edit, and execute Python code with syntax highlighting. See your results instantly and experiment with different scripts.</p>
            <p>Features include:</p>
            <ul>
                <li>Syntax highlighting</li>
                <li>Code execution</li>
                <li>Output display</li>
            </ul>
        </div>
        """, unsafe_allow_html=True)
        
        st.markdown("""
        <div style="background-color: #FFFFFF; padding: 20px; border-radius: 10px; margin-top: 20px; height: 200px;">
            <h3 style="color: #2196F3;">📊 Visualizations</h3>
            <p>Create and customize visualizations from your datasets. Explore data through charts, graphs, and interactive plots.</p>
            <p>Visualization types:</p>
            <ul>
                <li>Bar charts & histograms</li>
                <li>Scatter plots</li>
                <li>Line charts</li>
                <li>And more!</li>
            </ul>
        </div>
        """, unsafe_allow_html=True)

    with col2:
        st.markdown("""
        <div style="background-color: #FFFFFF; padding: 20px; border-radius: 10px; height: 200px;">
            <h3 style="color: #2196F3;">🗃️ Dataset Explorer</h3>
            <p>Browse and analyze datasets from the HuggingFace Hub. Filter, sort, and examine data with ease.</p>
            <p>Explorer features:</p>
            <ul>
                <li>Dataset previews</li>
                <li>Basic statistics</li>
                <li>Filtering options</li>
                <li>Data exports</li>
            </ul>
        </div>
        """, unsafe_allow_html=True)
        
        st.markdown("""
        <div style="background-color: #FFFFFF; padding: 20px; border-radius: 10px; margin-top: 20px; height: 200px;">
            <h3 style="color: #2196F3;">📈 Model Metrics</h3>
            <p>Analyze model performance with detailed metrics and comparisons. Understand how your models perform on different datasets.</p>
            <p>Metrics available:</p>
            <ul>
                <li>Accuracy, precision, recall</li>
                <li>Confusion matrices</li>
                <li>Performance comparisons</li>
                <li>Custom metric calculations</li>
            </ul>
        </div>
        """, unsafe_allow_html=True)
    
    # Getting started section
    st.markdown("""
    <div style="background-color: #FFFFFF; padding: 20px; border-radius: 10px; margin-top: 20px;">
        <h3 style="color: #2196F3;">Getting Started</h3>
        <p>To begin exploring, select a page from the sidebar navigation. You can:</p>
        <ol>
            <li>Write and test Python code in the <b>Code Editor</b></li>
            <li>Search for and explore datasets in the <b>Dataset Explorer</b></li>
            <li>Create visualizations in the <b>Visualizations</b> section</li>
            <li>Analyze model performance in the <b>Model Metrics</b> page</li>
        </ol>
        <p>Ready to dive in? Select a page from the sidebar to get started!</p>
    </div>
    """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()