import streamlit as st
import plotly.express as px
import pandas as pd
from modules import ui, reports
from modules.glpi_client import GLPIClient

# Page Config
st.set_page_config(
    page_title="GLPI Analytics Dashboard",
    page_icon="📊",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Apply custom styling
ui.inject_custom_css()

def main():
    st.title("GLPI Executive Dashboard")
    st.markdown("### Bem-vindo ao seu painel de controle.")

# Init Client
    client = GLPIClient()
    client.init_session()
    
    # Load Data
    df = client.get_tickets(200)
    kpis = client.get_kpis(df)

    # Sidebar
    with st.sidebar:
        st.header("📊 Filtros")
        
        # Date Range
        min_date = df['date'].min().date()
        max_date = df['date'].max().date()
        
        date_range = st.date_input(
            "Período de Análise",
            value=(min_date, max_date),
            min_value=min_date,
            max_value=max_date
        )
        
        st.divider()
        st.markdown("### 📥 Exportar")
        
        # Prepare data for export
        csv_data = reports.convert_df_to_csv(df)
        pdf_data = reports.generate_pdf(df, kpis)
        
        st.download_button(
            label="Download CSV",
            data=csv_data,
            file_name="glpi_data.csv",
            mime="text/csv",
        )
        
        st.download_button(
            label="Download PDF Report",
            data=pdf_data,
            file_name="glpi_report.pdf",
            mime="application/pdf",
        )

        st.divider()
        st.markdown("### Configurações")
        st.checkbox("Auto-refresh", value=True)

    # Top KPI Row
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        ui.metric_card("Total Chamados", str(kpis['total']), "+12%", is_positive=True, color_bar="#C084FC")
    with col2:
        ui.metric_card("Solucionados", str(kpis['solved']), "+8%", is_positive=True, color_bar="#5EEAD4")
    with col3:
        ui.metric_card("Em Aberto", str(kpis['open']), "-5%", is_positive=True, color_bar="#FF9F46") # Less open is positive likely
    with col4:
        ui.metric_card("Taxa de Sucesso", f"{kpis['success_rate']:.1f}%", "+2%", is_positive=True, color_bar="#D4FF5F")

    # Charts Section
    st.markdown("### 📈 Análise de Tendências")
    
    # Create two columns for charts
    c1, c2 = st.columns(2)
    
    with c1:
        st.markdown("#### Chamados por Categoria")
        # Plotly Pie Pattern
        category_counts = df['category'].value_counts().reset_index()
        category_counts.columns = ['Categoria', 'Chamados']
        
        # Neon palette
        colors = ['#C084FC', '#5EEAD4', '#D4FF5F', '#FF9F46', '#F87171']
        
        fig_cat = px.pie(
            category_counts, 
            values='Chamados', 
            names='Categoria', 
            hole=0.7,
            color_discrete_sequence=colors
        )
        fig_cat.update_layout(
            paper_bgcolor="rgba(0,0,0,0)",
            plot_bgcolor="rgba(0,0,0,0)",
            font=dict(color="#fafafa"),
            showlegend=True,
            margin=dict(t=30, b=0, l=0, r=0),
            legend=dict(orientation="h", yanchor="bottom", y=-0.2, xanchor="center", x=0.5)
        )
        # Remove stroke
        fig_cat.update_traces(marker=dict(line=dict(width=0)))
        
        st.plotly_chart(fig_cat, use_container_width=True)
        
    with c2:
        st.markdown("#### Evolução Diária")
        # Time series mock
        daily_counts = df.groupby(df['date'].dt.date).size().reset_index(name='Chamados')
        
        fig_line = px.area(
            daily_counts, 
            x='date', 
            y='Chamados',
            markers=False,
        )
        
        fig_line.update_traces(
            line_color='#5EEAD4', 
            fillcolor="rgba(94, 234, 212, 0.1)", # Transparent fill
            line_shape='spline',
            line_width=3
        )
        
        fig_line.update_layout(
            paper_bgcolor="rgba(0,0,0,0)",
            plot_bgcolor="rgba(0,0,0,0)",
            font=dict(color="#A0A0B0"),
            xaxis=dict(showgrid=False, title=None, tickformat="%d/%m"),
            yaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.05)', title=None, zeroline=False),
            margin=dict(t=20, b=20, l=0, r=0),
            hovermode="x unified"
        )
        st.plotly_chart(fig_line, use_container_width=True)

    # Recent Data Table
    st.markdown("### 📋 Chamados Recentes")
    
    # Styled dataframe
    st.dataframe(
        df[['id', 'name', 'status', 'category', 'date', 'priority']].sort_values('date', ascending=False).head(10),
        use_container_width=True,
        hide_index=True
    )

if __name__ == "__main__":
    main()
