from nicegui import ui, app
from rt_commission_dashboard.ui.theme import Theme
from rt_commission_dashboard.ui.layout import layout
from rt_commission_dashboard.core.db_handler import get_db_handler
from rt_commission_dashboard.core.i18n import t
from rt_commission_dashboard.core.currency import format_currency

@layout
def dashboard_page():
    user = app.storage.user.get('user_info', {})
    db = get_db_handler()
    
    # ... (Title omitted for brevity if unchanged, but I need to make sure import works)
    
    # Title
    with ui.row().classes('items-center mb-6'):
        ui.icon('dashboard', size='md', color=Theme.SECONDARY)
        Theme.title(t('dash.title'))
    
    # --- Filter Logic ---
    from datetime import datetime
    current_year = datetime.now().year
    
    # Get viewable users (Self + Downline, or All if Admin)
    # Filterable View: Only show if there are options other than self, OR if user wants to see time filters
    viewable_users = db.get_viewable_users(user['id'], user.get('role', 'ctv'))
    
    # Options construction
    user_options = {u['id']: u['label'] for u in viewable_users}
    is_admin = user.get('role') == 'admin'
    if is_admin:
        user_options = {'global': f"Global Stats (Admin)", **user_options}
        default_target = 'global'
    else:
        default_target = user['id']

    # Refreshable Content
    @ui.refreshable
    def render_dashboard_content(target_id, month, year):
        # Fetch Data
        kpis = db.get_kpi_stats(target_id, month=month, year=year)
        monthly_data = db.get_monthly_sales(target_id, year=year)
            
        # --- KPI Cards ---
        with ui.row().classes('w-full gap-4'):
            _kpi_card(t('dash.total_revenue'), format_currency(kpis['revenue']), 'attach_money', 'green')
            _kpi_card(t('dash.total_commission'), format_currency(kpis['commission']), 'payments', 'blue')
            _kpi_card(t('dash.new_customers'), str(kpis['new_customers']), 'person_add', 'orange')
            _kpi_card(t('dash.network_size'), str(kpis['network_size']), 'hub', 'purple')

        # --- Commission Breakdown ---
        ui.label(t('dash.comm_breakdown')).classes('text-lg font-bold mt-6 mb-2 text-gray-400')
        with ui.row().classes('w-full gap-4'):
            _kpi_card(t('dash.comm_direct'), format_currency(kpis['comm_direct']), 'store', 'teal')
            _kpi_card(t('dash.comm_shared'), format_currency(kpis['comm_shared']), 'share', 'cyan')
            _kpi_card(t('dash.comm_received'), format_currency(kpis['comm_received']), 'move_to_inbox', 'indigo')
            _kpi_card(t('dash.comm_override'), format_currency(kpis['comm_override']), 'group_work', 'pink')

        # --- Charts ---
        months = [row[0] for row in monthly_data]
        sales = [row[1] for row in monthly_data]
        
        if not months:
            months = ['Jan', 'Feb', 'Mar']
            sales = [0, 0, 0]

        with Theme.card().classes('w-full mt-6'):
            ui.label(t('dash.chart_title')).classes('text-xl font-bold mb-4')
            ui.plotly({
                'data': [
                    {'x': months, 'y': sales, 'type': 'bar', 'name': 'Sales', 'marker': {'color': '#6366f1'}},
                    {'x': months, 'y': sales, 'type': 'scatter', 'mode': 'lines+markers', 'name': 'Trend', 'line': {'color': '#10b981'}}
                ],
                'layout': {
                    'margin': {'l': 40, 'r': 20, 't': 20, 'b': 40},
                    'plot_bgcolor': 'rgba(0,0,0,0)',
                    'paper_bgcolor': 'rgba(0,0,0,0)',
                    'font': {'color': '#94a3b8'},
                    'showlegend': True,
                    'xaxis': {'showgrid': False, 'type': 'category'},
                    'yaxis': {'gridcolor': '#334155'}
                }
            }).classes('w-full h-80')

    # --- Render Filters ---
    with ui.row().classes('mb-4 items-center gap-4'):
        
        # 1. User Selector (Only if > 1 option)
        target_select = None
        if len(user_options) > 0: # Always >0 (self)
             if len(user_options) > 1 or is_admin:
                target_select = ui.select(
                    options=user_options, 
                    value=default_target,
                    label=t('nav.users'),
                    on_change=lambda: refresh_all()
                ).classes('w-64').props('outlined dense dark use-input filter')
        
        # 2. Year Selector
        year_select = ui.select(
            options=[str(y) for y in range(current_year, current_year-5, -1)], 
            value=str(current_year), 
            label=t('rep.year'),
            on_change=lambda: refresh_all()
        ).classes('w-32').props('outlined dense dark')
        
        # 3. Month Selector
        month_select = ui.select(
            options={f"{m:02d}": datetime(2000, m, 1).strftime('%B') for m in range(1, 13)}, 
            value=None, 
            label=t('rep.month'),
            on_change=lambda: refresh_all()
        ).classes('w-40').props('outlined dense dark clearable')
        
        def refresh_all():
            t_id = target_select.value if target_select else default_target
            m = month_select.value
            y = year_select.value
            render_dashboard_content.refresh(t_id, m, y)
            
    # Initial Render
    render_dashboard_content(default_target, None, str(current_year))

def _kpi_card(title, value, icon, color):
    with Theme.card().classes('flex-1 min-w-[200px]'):
        with ui.row().classes('items-center gap-4'):
            ui.icon(icon).classes(f'text-3xl text-{color}-500')
            with ui.column().classes('gap-0'):
                ui.label(title).classes('text-gray-400 text-sm')
                ui.label(value).classes('text-2xl font-bold')
