import streamlit as st
import pandas as pd
from datetime import datetime

def render_home():
    """Render the home page with model overview and statistics"""
    st.title("🤗 Hugging Face Model Manager")

    st.markdown(
        """
        Welcome to your personal Hugging Face model management dashboard. 
        From here, you can view, create, and manage your machine learning models.
        """
    )

    # Check if we have models loaded
    if not st.session_state.get("models"):
        with st.spinner("Loading your models..."):
            try:
                st.session_state.models = st.session_state.client.get_user_models()
            except Exception as e:
                st.error(f"Error loading models: {str(e)}")

    # Model Statistics Dashboard
    st.markdown("### 📊 Model Statistics")

    # Key statistics in cards
    col1, col2, col3 = st.columns([1, 1, 1])

    with col1:
        # Total models count
        total_models = len(st.session_state.models)
        st.markdown(
            f"""
            <div class="tooltip" style="width: 100%;">
                <div style="padding: 20px; background-color: #F9FAFB; border-radius: 10px; border: 1px solid #E5E7EB; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); transition: all 0.3s;">
                    <div style="font-size: 36px; color: #6366F1; font-weight: bold;">
                        {total_models}
                    </div>
                    <div style="color: #6B7280; font-weight: 500;">
                        Total Models
                    </div>
                </div>
                <span class="tooltip-text">Total number of models you've created</span>
            </div>
            """,
            unsafe_allow_html=True,
        )

    with col2:
        # Total downloads (sum from all models)
        total_downloads = sum(
            getattr(model, "downloads", 0) for model in st.session_state.models
        )
        st.markdown(
            f"""
            <div class="tooltip" style="width: 100%;">
                <div style="padding: 20px; background-color: #F9FAFB; border-radius: 10px; border: 1px solid #E5E7EB; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); transition: all 0.3s;">
                    <div style="font-size: 36px; color: #10B981; font-weight: bold;">
                        {total_downloads:,}
                    </div>
                    <div style="color: #6B7280; font-weight: 500;">
                        Total Downloads
                    </div>
                </div>
                <span class="tooltip-text">Cumulative downloads across all your models</span>
            </div>
            """,
            unsafe_allow_html=True,
        )

    with col3:
        # Calculate total likes
        total_likes = sum(
            getattr(model, "likes", 0) for model in st.session_state.models
        )
        st.markdown(
            f"""
            <div class="tooltip" style="width: 100%;">
                <div style="padding: 20px; background-color: #F9FAFB; border-radius: 10px; border: 1px solid #E5E7EB; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); transition: all 0.3s;">
                    <div style="font-size: 36px; color: #FF9D96; font-weight: bold;">
                        {total_likes}
                    </div>
                    <div style="color: #6B7280; font-weight: 500;">
                        Total Likes
                    </div>
                </div>
                <span class="tooltip-text">Cumulative likes across all your models</span>
            </div>
            """,
            unsafe_allow_html=True,
        )

    # Quick Actions with improved styling
    st.markdown("### 🚀 Quick Actions")

    quick_actions_col1, quick_actions_col2 = st.columns([1, 1])

    with quick_actions_col1:
        if st.button(
            "➕ Create New Repository", key="create_repo_home", use_container_width=True
        ):
            st.session_state.page = "repository_management"
            st.experimental_rerun()

    with quick_actions_col2:
        if st.button(
            "🔄 Refresh Models", key="refresh_models_home", use_container_width=True
        ):
            with st.spinner("Refreshing models..."):
                try:
                    st.session_state.models = st.session_state.client.get_user_models()
                    st.success("Models refreshed!")
                except Exception as e:
                    st.error(f"Error refreshing models: {str(e)}")

    # Your Models section
    st.markdown("### 📚 Your Models")

    if not st.session_state.models:
        st.info(
            "You don't have any models yet. Click 'Create New Repository' to get started!"
        )
    else:
        # Create dataframe from models list for display
        models_data = []
        for model in st.session_state.models:
            try:
                # Extract key data
                last_modified = (
                    datetime.fromisoformat(model.lastModified.replace("Z", "+00:00"))
                    if hasattr(model, "lastModified")
                    else None
                )
                
                model_data = {
                    "Model Name": model.modelId.split("/")[-1],
                    "Full ID": model.modelId,
                    "Downloads": getattr(model, "downloads", 0),
                    "Likes": getattr(model, "likes", 0),
                    "Last Modified": last_modified,
                    "Private": getattr(model, "private", False),
                }
                models_data.append(model_data)
            except Exception as e:
                st.warning(f"Error processing model {getattr(model, 'modelId', 'unknown')}: {str(e)}")

        # Sorting
        sort_options = ["Last Modified", "Downloads", "Likes", "Model Name"]
        sort_by = st.selectbox("Sort by", sort_options, index=0)
        
        # Create DataFrame and sort
        if models_data:
            df = pd.DataFrame(models_data)
            if sort_by == "Last Modified":
                df = df.sort_values(by=sort_by, ascending=False)
            elif sort_by in ["Downloads", "Likes"]:
                df = df.sort_values(by=sort_by, ascending=False)
            else:
                df = df.sort_values(by=sort_by)
            
            # Format the Last Modified date
            df["Last Modified"] = df["Last Modified"].apply(
                lambda x: x.strftime("%b %d, %Y") if pd.notnull(x) else "N/A"
            )
            
            # Display models as cards
            for i, row in df.iterrows():
                with st.container():
                    col1, col2 = st.columns([3, 1])
                    with col1:
                        st.markdown(
                            f"""
                            <div style="padding: 16px; background-color: #F9FAFB; border-radius: 8px; border: 1px solid #E5E7EB; margin-bottom: 16px; cursor: pointer; transition: all 0.3s;" 
                                 onclick="window.open('https://huggingface.co/{row['Full ID']}', '_blank')">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <h3 style="margin: 0; color: #111827;">{row['Model Name']}</h3>
                                        <p style="margin: 4px 0 0 0; color: #6B7280; font-size: 14px;">{row['Full ID']}</p>
                                    </div>
                                    <div style="display: flex; align-items: center;">
                                        <div style="margin-right: 16px; text-align: center;">
                                            <div style="font-weight: bold; color: #10B981;">{row['Downloads']:,}</div>
                                            <div style="font-size: 12px; color: #6B7280;">downloads</div>
                                        </div>
                                        <div style="margin-right: 16px; text-align: center;">
                                            <div style="font-weight: bold; color: #FF9D96;">{row['Likes']}</div>
                                            <div style="font-size: 12px; color: #6B7280;">likes</div>
                                        </div>
                                        <div style="text-align: center;">
                                            <div style="font-weight: bold; color: #6366F1;">{row['Last Modified']}</div>
                                            <div style="font-size: 12px; color: #6B7280;">updated</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            """,
                            unsafe_allow_html=True,
                        )
                    with col2:
                        if st.button(
                            "📝 Manage", 
                            key=f"manage_{row['Full ID']}", 
                            use_container_width=True
                        ):
                            st.session_state.selected_model = row["Full ID"]
                            st.session_state.page = "model_details"
                            st.experimental_rerun()