@page "/trading"
@using TradingBot.Models
@using TradingBot.Services
@inject TradingBotService BotService
@implements IDisposable
@rendermode InteractiveServer

<PageTitle>Trading - TradingBot</PageTitle>

<div class="trading-page">
    <div class="page-header">
        <div>
            <h1>Trading Automatico</h1>
            <p class="subtitle">Applica strategie agli asset e monitora le operazioni in tempo reale</p>
        </div>
        <div class="header-controls">
            <button class="btn-secondary">
                <span class="bi bi-download"></span>
                Esporta Report
            </button>
            <button class="btn-toggle @(BotService.Status.IsRunning ? "active" : "")" @onclick="ToggleBot">
                <span class="bi @(BotService.Status.IsRunning ? "bi-pause-circle-fill" : "bi-play-circle-fill")"></span>
                @(BotService.Status.IsRunning ? "Stop Trading" : "Avvia Trading")
            </button>
        </div>
    </div>

    <!-- Assets Grid -->
    <div class="assets-section">
        <div class="section-header">
            <h2>Asset Monitorati</h2>
            <div class="filters">
                <select class="filter-select">
                    <option>Tutti gli Asset</option>
                    <option>Solo Attivi</option>
                    <option>Solo Inattivi</option>
                </select>
                <button class="btn-icon">
                    <span class="bi bi-funnel"></span>
                </button>
            </div>
        </div>

        <div class="assets-grid">
            @foreach (var config in BotService.AssetConfigurations.Values.OrderBy(c => c.Symbol))
            {
                var stats = BotService.AssetStatistics.TryGetValue(config.Symbol, out var s) ? s : null;
                var latestPrice = BotService.GetLatestPrice(config.Symbol);
                
                <div class="asset-trading-card @(config.IsEnabled ? "enabled" : "disabled")">
                    <div class="asset-header">
                        <div class="asset-title">
                            <span class="asset-icon">@config.Symbol.Substring(0, 1)</span>
                            <div class="asset-name-group">
                                <span class="name">@config.Name</span>
                                <span class="symbol">@config.Symbol</span>
                            </div>
                        </div>
                        <label class="toggle-switch">
                            <input type="checkbox" 
                                   checked="@config.IsEnabled" 
                                   @onchange="(e) => ToggleAsset(config.Symbol, (bool)e.Value!)" />
                            <span class="toggle-slider"></span>
                        </label>
                    </div>

                    @if (latestPrice != null)
                    {
                        <div class="asset-price-info">
                            <div class="current-price">$@latestPrice.Price.ToString("N2")</div>
                            <div class="price-change @(latestPrice.Change24h >= 0 ? "positive" : "negative")">
                                <span class="bi @(latestPrice.Change24h >= 0 ? "bi-arrow-up" : "bi-arrow-down")"></span>
                                @Math.Abs(latestPrice.Change24h).ToString("F2")%
                            </div>
                        </div>
                    }
                    else
                    {
                        <div class="asset-price-info">
                            <div class="current-price loading">Loading...</div>
                        </div>
                    }

                    <div class="asset-strategy">
                        <div class="strategy-label">Strategia Applicata</div>
                        <div class="strategy-name">
                            <span class="bi bi-diagram-3"></span>
                            @config.StrategyName
                        </div>
                    </div>

                    <div class="asset-metrics">
                        <div class="metric">
                            <span class="metric-label">Holdings</span>
                            <span class="metric-value">@config.CurrentHoldings.ToString("F4")</span>
                        </div>
                        <div class="metric">
                            <span class="metric-label">Valore</span>
                            <span class="metric-value">$@((config.CurrentBalance + config.CurrentHoldings * (latestPrice?.Price ?? 0)).ToString("N2"))</span>
                        </div>
                        <div class="metric">
                            <span class="metric-label">Profitto</span>
                            <span class="metric-value @(config.TotalProfit >= 0 ? "profit" : "loss")">
                                $@config.TotalProfit.ToString("N2")
                            </span>
                        </div>
                        <div class="metric">
                            <span class="metric-label">Trades</span>
                            <span class="metric-value">@(stats?.TotalTrades ?? 0)</span>
                        </div>
                    </div>

                    <div class="asset-actions">
                        <button class="btn-secondary btn-sm" @onclick="() => OpenAssetConfig(config.Symbol)">
                            <span class="bi bi-gear"></span>
                            Configura
                        </button>
                        <button class="btn-secondary btn-sm" @onclick="() => ViewChart(config.Symbol)">
                            <span class="bi bi-graph-up"></span>
                            Grafico
                        </button>
                    </div>
                </div>
            }
        </div>
    </div>

    <!-- Recent Trades -->
    <div class="trades-section">
        <div class="section-header">
            <h2>Operazioni Recenti</h2>
            <button class="btn-secondary btn-sm">
                <span class="bi bi-clock-history"></span>
                Vedi Tutto
            </button>
        </div>

        @if (BotService.Trades.Count == 0)
        {
            <div class="empty-state">
                <span class="bi bi-inbox"></span>
                <p>Nessuna operazione ancora</p>
                <p class="hint">Avvia il trading per iniziare a eseguire operazioni</p>
            </div>
        }
        else
        {
            <div class="trades-table">
                <div class="table-header">
                    <div>Asset</div>
                    <div>Tipo</div>
                    <div>Quantità</div>
                    <div>Prezzo</div>
                    <div>Valore</div>
                    <div>Strategia</div>
                    <div>Data/Ora</div>
                </div>
                @foreach (var trade in BotService.Trades.Take(20))
                {
                    <div class="table-row @(trade.IsBot ? "bot-trade" : "")">
                        <div class="cell-asset">
                            <span class="asset-badge">@trade.Symbol</span>
                        </div>
                        <div class="cell-type @(trade.Type == TradeType.Buy ? "buy" : "sell")">
                            <span class="bi @(trade.Type == TradeType.Buy ? "bi-arrow-down-circle-fill" : "bi-arrow-up-circle-fill")"></span>
                            @(trade.Type == TradeType.Buy ? "BUY" : "SELL")
                        </div>
                        <div>@trade.Amount.ToString("F6")</div>
                        <div>$@trade.Price.ToString("N2")</div>
                        <div class="cell-value">$@((trade.Amount * trade.Price).ToString("N2"))</div>
                        <div class="cell-strategy">
                            @if (trade.IsBot)
                            {
                                <span class="strategy-tag">
                                    <span class="bi bi-robot"></span>
                                    @trade.Strategy
                                </span>
                            }
                            else
                            {
                                <span class="manual-tag">Manuale</span>
                            }
                        </div>
                        <div class="cell-time">@trade.Timestamp.ToLocalTime().ToString("dd/MM HH:mm:ss")</div>
                    </div>
                }
            </div>
        }
    </div>
</div>

@code {
    protected override void OnInitialized()
    {
        BotService.OnStatusChanged += HandleUpdate;
        BotService.OnTradeExecuted += HandleTradeExecuted;
        BotService.OnPriceUpdated += HandlePriceUpdate;
        
        if (!BotService.Status.IsRunning)
        {
            BotService.Start();
        }
    }

    private void ToggleBot()
    {
        if (BotService.Status.IsRunning)
            BotService.Stop();
        else
            BotService.Start();
    }

    private void ToggleAsset(string symbol, bool enabled)
    {
        BotService.ToggleAsset(symbol, enabled);
    }

    private void OpenAssetConfig(string symbol)
    {
        // TODO: Open asset configuration modal
    }

    private void ViewChart(string symbol)
    {
        // TODO: Navigate to market analysis with selected symbol
    }

    private void HandleUpdate() => InvokeAsync(StateHasChanged);
    private void HandleTradeExecuted(Trade trade) => InvokeAsync(StateHasChanged);
    private void HandlePriceUpdate(string symbol, MarketPrice price) => InvokeAsync(StateHasChanged);

    public void Dispose()
    {
        BotService.OnStatusChanged -= HandleUpdate;
        BotService.OnTradeExecuted -= HandleTradeExecuted;
        BotService.OnPriceUpdated -= HandlePriceUpdate;
    }
}
