"""Dashboard layout components."""

from dash import html, dcc
import dash_bootstrap_components as dbc

from .components import MetricCard, create_tabs
from .plots import create_equity_curve, create_returns_histogram, create_drawdown_chart

def create_layout(portfolio, metrics, monte_carlo):
    """Create main dashboard layout."""
    
    return dbc.Container([
        # Header with gradient background and logo
        dbc.Row([
            dbc.Col([
                html.Div([
                    html.Div([
                        html.Img(
                            src="/assets/logofinalpng.png",
                            height="80px",
                            style={
                                "backgroundColor": "#000000",
                                "padding": "15px 25px",
                                "borderRadius": "20px",
                                "border": "3px solid #444",
                                "boxShadow": "0 8px 25px rgba(0,0,0,0.6)",
                                "marginBottom": "25px",
                                "transform": "scale(1.1)"
                            }
                        )
                    ], className="text-center"),
                    html.H1([
                        html.I(className="fas fa-chart-line me-3"),
                        "Strategy Performance Dashboard"
                    ], className="text-center mb-2", style={"font-weight": "300", "font-size": "3rem"}),
                    html.P("Comprehensive analysis of your trading strategy performance", 
                           className="text-center text-muted mb-4", style={"font-size": "1.2rem"})
                ], style={
                    "background": "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                    "padding": "40px",
                    "border-radius": "20px",
                    "margin-bottom": "30px",
                    "box-shadow": "0 10px 30px rgba(0,0,0,0.3)"
                })
            ])
        ]),
        
        # Portfolio composition info
        dbc.Row([
            dbc.Col([
                create_portfolio_composition_card(portfolio)
            ], width=12)
        ], className="mb-4"),
        
        # Key Metrics Row with enhanced cards
        dbc.Row([
            dbc.Col([
                create_enhanced_metric_card("Total Return", f"{metrics.total_return:.2%}", 
                                           "fas fa-arrow-trend-up", "success", 
                                           "Overall portfolio return from start to finish")
            ], width=3),
            dbc.Col([
                create_enhanced_metric_card("Sharpe Ratio", f"{metrics.sharpe_ratio:.2f}", 
                                           "fas fa-balance-scale", "info",
                                           "Risk-adjusted return (>1.0 is good, >2.0 is excellent)")
            ], width=3),
            dbc.Col([
                create_enhanced_metric_card("Max Drawdown", f"{metrics.max_drawdown:.2%}", 
                                           "fas fa-arrow-trend-down", "warning",
                                           "Largest peak-to-trough decline")
            ], width=3),
            dbc.Col([
                create_enhanced_metric_card("Win Rate", f"{metrics.win_rate:.1%}", 
                                           "fas fa-target", "primary",
                                           "Percentage of profitable trades")
            ], width=3),
        ], className="mb-5"),
        
        # Main Content Tabs
        create_tabs(portfolio, metrics, monte_carlo),
        
        # Footer
        html.Hr(style={"margin-top": "50px"}),
        html.Footer([
            html.Div([
                html.Img(
                    src="/assets/logofinalpng.png",
                    height="45px",
                    className="me-3",
                    style={
                        "backgroundColor": "#000000",
                        "padding": "8px 12px",
                        "borderRadius": "12px",
                        "border": "2px solid #444",
                        "boxShadow": "0 4px 15px rgba(0,0,0,0.4)"
                    }
                ),
                html.Span([
                    "Generated by ",
                    html.Strong("Enode Backtester"),
                    " • Professional quantitative analysis framework"
                ], className="text-muted align-middle")
            ], className="text-center d-flex justify-content-center align-items-center", 
               style={"margin-bottom": "30px"})
        ])
        
    ], fluid=True)

def create_performance_tab(portfolio, metrics):
    """Performance analysis tab content."""
    
    return html.Div([
        # Explanation section
        html.Div([
            html.H5([html.I(className="fas fa-info-circle me-2"), "Performance Overview"]),
            html.P([
                "This section compares your strategy's performance against a buy-and-hold benchmark. The solid line shows ",
                "your strategy's equity curve, while the dotted line represents equal-weight allocation across all traded assets. ",
                "Outperforming the benchmark indicates your strategy adds value beyond passive investing."
            ])
        ], className="explanation"),
        
        dbc.Row([
            dbc.Col([
                dbc.Card([
                    dbc.CardHeader([html.I(className="fas fa-chart-line me-2"), "Equity Curve"]),
                    dbc.CardBody([
                        dcc.Graph(figure=create_equity_curve(portfolio))
                    ])
                ])
            ], width=8),
            dbc.Col([
                dbc.Card([
                    dbc.CardHeader([html.I(className="fas fa-table me-2"), "Performance Metrics"]),
                    dbc.CardBody([
                        create_metrics_table(metrics)
                    ])
                ])
            ], width=4),
        ])
    ])

def create_risk_tab(metrics, portfolio):
    """Risk analysis tab content."""
    
    # Extract returns from portfolio equity curve
    import pandas as pd
    equity_df = pd.DataFrame(portfolio.equity_curve, columns=['timestamp', 'equity'])
    equity_df['timestamp'] = pd.to_datetime(equity_df['timestamp'])
    returns = equity_df['equity'].pct_change().dropna()
    
    return html.Div([
        # Risk explanation
        html.Div([
            html.H5([html.I(className="fas fa-shield-alt me-2"), "Risk Analysis"]),
            html.P([
                "Risk analysis helps you understand the volatility and potential losses of your strategy. ",
                "The returns distribution shows how often you can expect different return levels. ",
                "Drawdown analysis reveals the worst losing streaks you might experience. ",
                "VaR (Value at Risk) tells you the maximum loss you can expect 95% of the time."
            ])
        ], className="explanation"),
        
        dbc.Row([
            dbc.Col([
                dbc.Card([
                    dbc.CardHeader([html.I(className="fas fa-chart-bar me-2"), "Returns Distribution"]),
                    dbc.CardBody([
                        dcc.Graph(figure=create_returns_histogram(returns, metrics.var_95))
                    ])
                ]),
                html.Br(),
                dbc.Card([
                    dbc.CardHeader([html.I(className="fas fa-calculator me-2"), "Return Statistics"]),
                    dbc.CardBody([
                        create_return_stats_table(returns)
                    ])
                ])
            ], width=6),
            dbc.Col([
                dbc.Card([
                    dbc.CardHeader([html.I(className="fas fa-chart-area me-2"), "Drawdown Analysis"]),
                    dbc.CardBody([
                        dcc.Graph(figure=create_drawdown_chart(returns)),
                        html.Div([
                            html.H6("💡 Understanding Drawdowns"),
                            html.P([
                                "Drawdowns show how much your portfolio declined from its peak value. ",
                                "Smaller, shorter drawdowns indicate a more stable strategy. ",
                                f"Your maximum drawdown was {metrics.max_drawdown:.2%}, meaning at worst ",
                                "your portfolio was down this much from its highest point."
                            ], style={"font-size": "0.9rem"})
                        ], className="explanation")
                    ])
                ])
            ], width=6),
        ])
    ])

def create_portfolio_composition_card(portfolio):
    """Create portfolio composition display card."""
    
    # Extract symbols from trade log
    symbols = set()
    for trade in portfolio.trade_log:
        symbols.add(trade.symbol)
    
    if not symbols:
        symbols_text = "No trades executed"
        benchmark_text = "N/A"
    else:
        symbols_list = sorted(list(symbols))
        symbols_text = ", ".join(symbols_list)
        if len(symbols_list) == 1:
            benchmark_text = f"100% {symbols_list[0]}"
        else:
            pct_each = 100 / len(symbols_list)
            benchmark_text = f"{pct_each:.1f}% each: {', '.join(symbols_list)}"
    
    return dbc.Card([
        dbc.CardBody([
            dbc.Row([
                dbc.Col([
                    html.Div([
                        html.I(className="fas fa-chart-pie fa-2x mb-2", style={"color": "#17a2b8"}),
                        html.H5("Portfolio Universe", className="mb-1"),
                        html.P(symbols_text, className="mb-0", style={"font-size": "1.1rem", "font-weight": "500"})
                    ])
                ], width=6),
                dbc.Col([
                    html.Div([
                        html.I(className="fas fa-balance-scale fa-2x mb-2", style={"color": "#28a745"}),
                        html.H5("Buy & Hold Benchmark", className="mb-1"),
                        html.P(benchmark_text, className="mb-0", style={"font-size": "1.1rem", "font-weight": "500"})
                    ])
                ], width=6)
            ])
        ])
    ], style={"background": "linear-gradient(135deg, #2d2d2d 0%, #3d3d3d 100%)", "border": "1px solid #404040"})

def create_enhanced_metric_card(title, value, icon, color, description):
    """Create enhanced metric card with icon and description."""
    
    color_map = {
        "success": "#28a745",
        "info": "#17a2b8", 
        "warning": "#ffc107",
        "primary": "#007bff"
    }
    
    return dbc.Card([
        dbc.CardBody([
            html.Div([
                html.I(className=f"{icon} fa-2x mb-3", style={"color": color_map[color]}),
                html.H2(value, className="metric-value", style={"color": color_map[color]}),
                html.H6(title, className="metric-label"),
                html.P(description, className="text-muted", style={"font-size": "0.8rem", "margin-top": "10px"})
            ], className="text-center")
        ])
    ], className="metric-card h-100")

def create_metrics_table(metrics):
    """Create performance metrics table."""
    
    return html.Div([
        html.Table([
            html.Tbody([
                html.Tr([html.Td("Annualized Return"), html.Td(f"{metrics.annualized_return:.2%}")]),
                html.Tr([html.Td("Volatility"), html.Td(f"{metrics.volatility:.2%}")]),
                html.Tr([html.Td("Sortino Ratio"), html.Td(f"{metrics.sortino_ratio:.2f}")]),
                html.Tr([html.Td("Calmar Ratio"), html.Td(f"{metrics.calmar_ratio:.2f}")]),
                html.Tr([html.Td("VaR (95%)"), html.Td(f"{metrics.var_95:.2%}")]),
                html.Tr([html.Td("CVaR (95%)"), html.Td(f"{metrics.cvar_95:.2%}")]),
            ])
        ], className="table table-striped", style={"color": "#ffffff", "backgroundColor": "#2d2d2d"}),
        
        html.Div([
            html.H6("📖 Metric Explanations", className="mt-3 mb-2"),
            html.Ul([
                html.Li([html.Strong("Sortino Ratio: "), "Like Sharpe but only penalizes downside volatility"]),
                html.Li([html.Strong("Calmar Ratio: "), "Annual return divided by max drawdown"]),
                html.Li([html.Strong("VaR: "), "Expected loss in worst 5% of cases"]),
                html.Li([html.Strong("CVaR: "), "Average loss when VaR threshold is exceeded"])
            ], style={"font-size": "0.85rem", "color": "#cccccc"})
        ], className="explanation")
    ])

def create_return_stats_table(returns):
    """Create detailed return statistics table."""
    
    import numpy as np
    
    if len(returns) == 0:
        return html.P("No return data available", className="text-muted")
    
    # Calculate statistics
    mean_daily = returns.mean()
    std_daily = returns.std()
    mean_annual = mean_daily * 252
    std_annual = std_daily * np.sqrt(252)
    
    return html.Table([
        html.Thead([
            html.Tr([
                html.Th("Metric", style={"color": "#ffffff"}),
                html.Th("Value", style={"color": "#ffffff"})
            ])
        ]),
        html.Tbody([
            html.Tr([html.Td("Mean Daily Return"), html.Td(f"{mean_daily:.4f} ({mean_daily*100:.3f}%)")]),
            html.Tr([html.Td("Std Daily Return"), html.Td(f"{std_daily:.4f} ({std_daily*100:.3f}%)")]),
            html.Tr([html.Td("Mean Annual Return"), html.Td(f"{mean_annual:.4f} ({mean_annual*100:.2f}%)")]),
            html.Tr([html.Td("Annual Volatility"), html.Td(f"{std_annual:.4f} ({std_annual*100:.2f}%)")]),
            html.Tr([html.Td("Min Return"), html.Td(f"{returns.min():.4f} ({returns.min()*100:.3f}%)")]),
            html.Tr([html.Td("Max Return"), html.Td(f"{returns.max():.4f} ({returns.max()*100:.3f}%)")]),
            html.Tr([html.Td("Median Return"), html.Td(f"{returns.median():.4f} ({returns.median()*100:.3f}%)")]),
        ])
    ], className="table table-striped", style={"color": "#ffffff", "backgroundColor": "#2d2d2d"})