@using TradingBot.Models
@using TradingBot.Services
@inject TradingBotService BotService

<div class="asset-settings-modal @(IsOpen ? "open" : "")">
    <div class="modal-overlay" @onclick="Close"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3>
                <span class="bi bi-gear-fill"></span>
                Impostazioni {{Config?.Symbol}}
            </h3>
            <button class="btn-close" @onclick="Close">
                <span class="bi bi-x-lg"></span>
            </button>
        </div>

        @if (Config != null)
        {
            <div class="modal-body">
                
                <!-- Basic Settings -->
                <div class="settings-section">
                    <h4 class="section-title">Impostazioni Base</h4>
                    
                    <div class="form-group">
                        <label>Stato</label>
                        <div class="toggle-wrapper">
                            <label class="toggle-switch">
                                <input type="checkbox" 
                                       @bind="Config.IsEnabled" />
                                <span class="toggle-slider"></span>
                            </label>
                            <span class="toggle-label">
                                {{Config.IsEnabled ? "Attivo" : "Inattivo"}}
                            </span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Bilancio Iniziale ($)</label>
                        <input type="number" 
                               class="form-input" 
                               @bind="Config.InitialBalance"
                               step="100"
                               min="0" />
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Bilancio Corrente ($)</label>
                            <input type="number" 
                                   class="form-input" 
                                   value="@Config.CurrentBalance"
                                   readonly />
                        </div>
                        <div class="form-group">
                            <label>Holdings</label>
                            <input type="number" 
                                   class="form-input" 
                                   value="@Config.CurrentHoldings"
                                   readonly />
                        </div>
                    </div>
                </div>

                <!-- Risk Management -->
                <div class="settings-section">
                    <h4 class="section-title">Gestione del Rischio</h4>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Stop Loss (%)</label>
                            <input type="number" 
                                   class="form-input" 
                                   @bind="Config.StopLossPercentage"
                                   step="0.5"
                                   min="0"
                                   max="100" />
                        </div>
                        <div class="form-group">
                            <label>Take Profit (%)</label>
                            <input type="number" 
                                   class="form-input" 
                                   @bind="Config.TakeProfitPercentage"
                                   step="0.5"
                                   min="0"
                                   max="100" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Dimensione Massima Posizione ($)</label>
                        <input type="number" 
                               class="form-input" 
                               @bind="Config.MaxPositionSize"
                               step="10"
                               min="0" />
                        <small class="form-hint">
                            Massimo valore totale della posizione in dollari
                        </small>
                    </div>
                </div>

                <!-- Trading Constraints -->
                <div class="settings-section">
                    <h4 class="section-title">Limiti di Trading</h4>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>Min Trade ($)</label>
                            <input type="number" 
                                   class="form-input" 
                                   @bind="Config.MinTradeAmount"
                                   step="1"
                                   min="1" />
                        </div>
                        <div class="form-group">
                            <label>Max Trade ($)</label>
                            <input type="number" 
                                   class="form-input" 
                                   @bind="Config.MaxTradeAmount"
                                   step="10"
                                   min="1" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Max Operazioni Giornaliere</label>
                        <input type="number" 
                               class="form-input" 
                               @bind="Config.MaxDailyTrades"
                               step="1"
                               min="1"
                               max="100" />
                        <small class="form-hint">
                            Operazioni oggi: {{Config.DailyTradeCount}} / {{Config.MaxDailyTrades}}
                        </small>
                    </div>
                </div>

                <!-- Strategy Parameters -->
                <div class="settings-section">
                    <h4 class="section-title">Parametri Strategia</h4>
                    
                    <div class="form-group">
                        <label>Strategia</label>
                        <input type="text" 
                               class="form-input" 
                               value="@Config.StrategyName"
                               readonly />
                    </div>

                    @if (Config.StrategyParameters.ContainsKey("ShortPeriod"))
                    {
                        <div class="form-row">
                            <div class="form-group">
                                <label>Periodo Corto</label>
                                <input type="number" 
                                       class="form-input" 
                                       value="@Config.StrategyParameters["ShortPeriod"]"
                                       @onchange="@((e) => UpdateStrategyParameter("ShortPeriod", e.Value))"
                                       step="1"
                                       min="5"
                                       max="50" />
                            </div>
                            <div class="form-group">
                                <label>Periodo Lungo</label>
                                <input type="number" 
                                       class="form-input" 
                                       value="@Config.StrategyParameters["LongPeriod"]"
                                       @onchange="@((e) => UpdateStrategyParameter("LongPeriod", e.Value))"
                                       step="1"
                                       min="10"
                                       max="100" />
                            </div>
                        </div>
                    }

                    @if (Config.StrategyParameters.ContainsKey("SignalThreshold"))
                    {
                        <div class="form-group">
                            <label>Soglia Segnale</label>
                            <input type="number" 
                                   class="form-input" 
                                   value="@Config.StrategyParameters["SignalThreshold"]"
                                   @onchange="@((e) => UpdateStrategyParameter("SignalThreshold", e.Value))"
                                   step="0.1"
                                   min="0"
                                   max="5" />
                        </div>
                    }
                </div>

                <!-- Current Stats -->
                <div class="settings-section stats-section">
                    <h4 class="section-title">Statistiche Correnti</h4>
                    
                    <div class="stats-grid">
                        <div class="stat-item">
                            <span class="stat-label">Profitto Totale</span>
                            <span class="stat-value @(Config.TotalProfit >= 0 ? "profit" : "loss")">
                                ${{Config.TotalProfit:N2}}
                            </span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">% Profitto</span>
                            <span class="stat-value @(Config.ProfitPercentage >= 0 ? "profit" : "loss")">
                                {{Config.ProfitPercentage:F2}}%
                            </span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Prezzo Medio Entrata</span>
                            <span class="stat-value">
                                ${{Config.AverageEntryPrice:N2}}
                            </span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">Ultimo Trade</span>
                            <span class="stat-value">
                                {{(Config.LastTradeTime?.ToLocalTime().ToString("HH:mm:ss") ?? "Mai")}}
                            </span>
                        </div>
                    </div>
                </div>

            </div>

            <div class="modal-footer">
                <button class="btn-secondary" @onclick="ResetToDefaults">
                    <span class="bi bi-arrow-counterclockwise"></span>
                    Reset
                </button>
                <button class="btn-primary" @onclick="SaveSettings">
                    <span class="bi bi-check-lg"></span>
                    Salva Modifiche
                </button>
            </div>
        }
    </div>
</div>

@code {
    [Parameter]
    public bool IsOpen { get; set; }

    [Parameter]
    public string? Symbol { get; set; }

    [Parameter]
    public EventCallback OnClose { get; set; }

    private AssetConfiguration? Config { get; set; }

    protected override void OnParametersSet()
    {
        if (IsOpen && !string.IsNullOrEmpty(Symbol))
        {
            LoadConfiguration();
        }
    }

    private void LoadConfiguration()
    {
        if (BotService.AssetConfigurations.TryGetValue(Symbol!, out var config))
        {
            // Create a copy to avoid modifying the original until saved
            Config = new AssetConfiguration
            {
                Symbol = config.Symbol,
                Name = config.Name,
                IsEnabled = config.IsEnabled,
                InitialBalance = config.InitialBalance,
                CurrentBalance = config.CurrentBalance,
                CurrentHoldings = config.CurrentHoldings,
                AverageEntryPrice = config.AverageEntryPrice,
                StrategyName = config.StrategyName,
                StrategyParameters = new Dictionary<string, object>(config.StrategyParameters),
                MaxPositionSize = config.MaxPositionSize,
                StopLossPercentage = config.StopLossPercentage,
                TakeProfitPercentage = config.TakeProfitPercentage,
                MinTradeAmount = config.MinTradeAmount,
                MaxTradeAmount = config.MaxTradeAmount,
                MaxDailyTrades = config.MaxDailyTrades,
                LastTradeTime = config.LastTradeTime,
                DailyTradeCount = config.DailyTradeCount,
                DailyTradeCountReset = config.DailyTradeCountReset
            };
        }
    }

    private void UpdateStrategyParameter(string key, object? value)
    {
        if (Config != null && value != null)
        {
            if (value is string strValue)
            {
                if (decimal.TryParse(strValue, out var decValue))
                {
                    Config.StrategyParameters[key] = decValue;
                }
                else if (int.TryParse(strValue, out var intValue))
                {
                    Config.StrategyParameters[key] = intValue;
                }
            }
        }
    }

    private void ResetToDefaults()
    {
        if (Config != null)
        {
            Config.InitialBalance = 1000m;
            Config.StopLossPercentage = 5m;
            Config.TakeProfitPercentage = 10m;
            Config.MaxPositionSize = 100m;
            Config.MinTradeAmount = 10m;
            Config.MaxTradeAmount = 500m;
            Config.MaxDailyTrades = 10;
            Config.StrategyParameters = new Dictionary<string, object>
            {
                { "ShortPeriod", 10 },
                { "LongPeriod", 30 },
                { "SignalThreshold", 0.5m }
            };
        }
    }

    private async Task SaveSettings()
    {
        if (Config != null && !string.IsNullOrEmpty(Symbol))
        {
            BotService.UpdateAssetConfiguration(Symbol, Config);
            await Close();
        }
    }

    private async Task Close()
    {
        IsOpen = false;
        await OnClose.InvokeAsync();
    }
}
