from dash import Input, Output, State, html, ALL, callback_context
import dash
from .constants import STRATEGY_OUTPUTS
from .helpers import (
    get_filtered_data,
    get_backtest_results,
    create_output_components
)
import pandas as pd
from .components import (
    create_equity_figure,
    create_underwater_figure,
    create_yearly_returns_figure,
    create_metrics_component
)

def register_remove_callback(app):
    @app.callback(
        [Output('selected-strategies', 'data'),
         Output('selected-count', 'children'),
         Output('equity-curve', 'figure'),
         Output('underwater-plot', 'figure'),
         Output('yearly-returns-plot', 'figure'),
         Output('strategy-header', 'children'),
         Output('strategy-metrics', 'children')],
        [Input({'type': 'remove-strategy', 'index': ALL}, 'n_clicks')],
        [State('selected-strategies', 'data'),
         State('backtest-results', 'data'),
         State('time-factor', 'value'),
         State('commission', 'value'),
         State('date-range-picker', 'start_date'),
         State('date-range-picker', 'end_date'),
         State('dashboard-mode', 'value')],
        prevent_initial_call=True
    )
    def remove_strategy(n_clicks_list, current_selection, backtest_results,
                        time_factor, commission, start_date, end_date, mode):
        if not callback_context.triggered:
            raise dash.exceptions.PreventUpdate

        trigger = callback_context.triggered[0]
        if trigger['value'] is None or trigger['value'] == 0:
            raise dash.exceptions.PreventUpdate

        button_id = eval(trigger['prop_id'].split('.')[0])
        index_to_remove = button_id['index']

        # Remove the strategy at the specified index
        updated_selection = [
            strategy for i, strategy in enumerate(current_selection)
            if i != index_to_remove
        ]

        # Convert string dates to datetime objects
        start_date = pd.to_datetime(start_date).date() if start_date else None
        end_date = pd.to_datetime(end_date).date() if end_date else None

        try:
            # Get filtered data
            data = get_filtered_data(start_date, end_date)

            # If there are still strategies left
            if updated_selection:
                # Recalculate backtest results for remaining strategies
                result_dict = get_backtest_results(
                    mode='combined',
                    current_selection=updated_selection,
                    data=data,
                    click_data=None,
                    time_factor=float(time_factor),
                    commission=float(commission) / 100
                )

                # Create header with improved styling
                header = html.Div([
                    html.Div("Combined Strategy Details",
                             style={'fontSize': '18px', 'fontWeight': 'bold', 'marginBottom': '8px'}),
                    html.Div([
                        html.Span("Parameters: ", style={'marginRight': '8px'}),
                        html.Div([
                            html.Div([
                                html.Span(f"({s['window']}, {s['threshold']:.2f})",
                                          style={'marginRight': '4px'}),
                                html.Button(
                                    "×",
                                    id={'type': 'remove-strategy', 'index': i},
                                    n_clicks=0,
                                    style={
                                        'border': 'none',
                                        'background': 'transparent',
                                        'color': '#666',
                                        'fontSize': '18px',
                                        'fontWeight': 'bold',
                                        'cursor': 'pointer',
                                        'padding': '2px 8px',
                                        'verticalAlign': 'middle',
                                        'lineHeight': '1',
                                        'transition': 'color 0.2s',
                                        'margin': '0 2px',
                                        'borderRadius': '50%'
                                    }
                                )
                            ], style={
                                'display': 'inline-flex',
                                'alignItems': 'center',
                                'margin': '2px 4px',
                                'padding': '4px 8px',
                                'backgroundColor': '#f0f0f0',
                                'border': '1px solid #ddd',
                                'borderRadius': '16px',
                                'fontSize': '14px'
                            }) for i, s in enumerate(updated_selection)
                        ], style={'display': 'inline-block'})
                    ], style={'marginBottom': '8px'}),
                    html.Div(f"Period: {start_date} to {end_date}")
                ])

                # Create figures
                equity_fig = create_equity_figure(result_dict)
                underwater_fig = create_underwater_figure(result_dict)
                yearly_returns_fig = create_yearly_returns_figure(result_dict)
                metrics = create_metrics_component(result_dict)

            else:
                # If no strategies left, return empty state
                empty_fig = {
                    'data': [],
                    'layout': {
                        'title': {
                            'text': 'No data to display',
                            'y': 0.95,
                            'x': 0.5,
                            'xanchor': 'center',
                            'yanchor': 'top',
                            'font': dict(size=16)
                        },
                        'showlegend': False,
                        'height': 300,
                        'template': 'plotly_white',
                        'xaxis': {'showgrid': False},
                        'yaxis': {'showgrid': False},
                        'margin': dict(l=50, r=50, t=50, b=50)
                    }
                }

                header = html.Div([
                    html.Div("Strategy Parameters",
                             style={'fontSize': '18px', 'fontWeight': 'bold', 'marginBottom': '8px'}),
                    html.Div("No strategies selected. Click on the heatmap to select strategies.")
                ])

                equity_fig = underwater_fig = yearly_returns_fig = empty_fig
                metrics = create_metrics_component(None)  # Will return empty white container

            return (
                updated_selection,
                f"Selected strategies: {len(updated_selection)}",
                equity_fig,
                underwater_fig,
                yearly_returns_fig,
                header,
                metrics
            )

        except Exception as e:
            print(f"Error in remove_strategy callback: {str(e)}")
            empty_fig = {
                'data': [],
                'layout': {
                    'title': 'Error occurred',
                    'showlegend': False
                }
            }
            error_header = html.Div([
                html.Div("Error",
                         style={'fontSize': '18px', 'fontWeight': 'bold', 'marginBottom': '8px'}),
                html.Div(f"An error occurred: {str(e)}")
            ])
            return (
                updated_selection,
                f"Selected strategies: {len(updated_selection)}",
                empty_fig,
                empty_fig,
                empty_fig,
                error_header,
                create_metrics_component(None)  # Will return empty white container
            )