import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../core/theme/app_theme.dart'; import '../../../core/widgets/glass_container.dart'; import '../../../core/widgets/status_badge.dart'; import '../../favorites/cubit/favorites_cubit.dart'; import '../../favorites/models/favorite_asset_model.dart'; import '../models/trade_model.dart'; import 'trade_calculation_card.dart'; import 'trade_detail_modal.dart'; class TradeCard extends StatelessWidget { final TradeModel trade; final VoidCallback? onAccept; final VoidCallback? onClose; final VoidCallback? onSettings; const TradeCard({ super.key, required this.trade, this.onAccept, this.onClose, this.onSettings, }); @override Widget build(BuildContext context) { final isBuy = trade.signalType == 'BUY' || trade.signalType == 'LONG'; final signalColor = isBuy ? AppTheme.primaryEmerald : AppTheme.accentRed; final isProposed = trade.isProposed; final isActive = trade.isActive; final isClosed = trade.isClosed; return BlocBuilder( builder: (context, favState) { double livePrice = 0.0; final keyUpper = (trade.isin.isNotEmpty ? trade.isin : trade.symbol).toUpperCase(); final match = favState.favoriteDetails.firstWhere( (f) => f.isin.toUpperCase() == keyUpper || f.symbol.toUpperCase() == keyUpper, orElse: () => const FavoriteAssetModel(isin: '', symbol: '', name: '', currentPrice: 0.0, change24h: 0.0), ); if (match.currentPrice > 0) { livePrice = match.currentPrice; } final pnlAbs = livePrice > 0 ? trade.calculateLivePnlAbs(livePrice) : trade.calculatedPnlAbs; final pnlPct = livePrice > 0 ? trade.calculateLivePnlPct(livePrice) : trade.calculatedPnlPct; final isPnlPos = pnlAbs >= 0; final pnlColor = isPnlPos ? AppTheme.primaryEmerald : AppTheme.accentRed; final currPrice = livePrice > 0 ? livePrice : trade.effectiveCurrentPrice; return GlassContainer( margin: const EdgeInsets.only(bottom: 14), padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Header Row: Signal, Symbol, Drift-Radar & Live PnL Row( children: [ Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), decoration: BoxDecoration( color: signalColor.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(8), border: Border.all(color: signalColor.withValues(alpha: 0.4)), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon(isBuy ? Icons.trending_up : Icons.trending_down, size: 14, color: signalColor), const SizedBox(width: 4), Text(trade.signalType, style: TextStyle(color: signalColor, fontWeight: FontWeight.bold, fontSize: 12)), ], ), ), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Flexible( child: Text( trade.companyName.isNotEmpty && trade.companyName != 'UNKNOWN' ? trade.companyName : (trade.symbol.isNotEmpty && trade.symbol != 'UNKNOWN' ? trade.symbol : (trade.isin.isNotEmpty ? trade.isin : 'Position')), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white), overflow: TextOverflow.ellipsis, ), ), if (trade.instrumentType.isNotEmpty) ...[ const SizedBox(width: 6), Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: Colors.white10, borderRadius: BorderRadius.circular(4), ), child: Text(trade.instrumentType, style: TextStyle(color: AppTheme.textSecondary, fontSize: 10, fontWeight: FontWeight.bold)), ), ], ], ), const SizedBox(height: 2), Text( '${trade.symbol.isNotEmpty ? trade.symbol : ""} ${trade.isin.isNotEmpty ? "• " + trade.isin : ""}', style: TextStyle(color: AppTheme.textMuted, fontSize: 11), ), ], ), ), // Status / PnL / Drift-Radar Badge if (isActive || isClosed) ...[ Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration( color: pnlColor.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(10), border: Border.all(color: pnlColor.withValues(alpha: 0.3)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( '${isPnlPos ? '+' : ''}€${pnlAbs.abs().toStringAsFixed(2)}', style: TextStyle(color: pnlColor, fontWeight: FontWeight.w900, fontSize: 14), ), Text( '${isPnlPos ? '+' : ''}${pnlPct.toStringAsFixed(2)}%', style: TextStyle(color: pnlColor, fontSize: 11, fontWeight: FontWeight.bold), ), ], ), ), ] else if (trade.isRejected) ...[ StatusBadge(label: 'ABGELEHNT', color: AppTheme.accentRed), ] else ...[ StatusBadge(label: 'VORSCHLAG', color: Colors.amber), ], ], ), // Active Drift Radar / Trailing Alert Indicator if (isActive) ...[ const SizedBox(height: 10), _buildDriftRadarBar(trade), ], // PENDING EXIT ALERT BANNER (Zero Auto-Close notification) if (isActive && trade.hasPendingExitAlert) ...[ const SizedBox(height: 10), Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: AppTheme.accentRed.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(10), border: Border.all(color: AppTheme.accentRed.withValues(alpha: 0.5)), ), child: Row( children: [ Icon(Icons.warning_amber_rounded, color: AppTheme.accentRed, size: 20), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'KI-Guardian Ratschlag: Position schließen!', style: TextStyle(color: AppTheme.accentRed, fontWeight: FontWeight.bold, fontSize: 12), ), if (trade.pendingExitReason.isNotEmpty) Text( trade.pendingExitReason, style: const TextStyle(color: Colors.white70, fontSize: 11), maxLines: 2, overflow: TextOverflow.ellipsis, ), ], ), ), if (onClose != null) ElevatedButton( onPressed: onClose, style: ElevatedButton.styleFrom( backgroundColor: AppTheme.accentRed, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), minimumSize: Size.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), child: const Text('Schließen', style: TextStyle(fontSize: 11, fontWeight: FontWeight.bold)), ), ], ), ), ], const SizedBox(height: 12), // Price Metrics Grid with Live Kurs & Trailing SL Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.black.withValues(alpha: 0.25), borderRadius: BorderRadius.circular(10), border: Border.all(color: Colors.white.withValues(alpha: 0.06)), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _priceItem( isActive || isClosed ? 'Einstieg' : 'Ziel-Einstieg', trade.actualEntryPrice > 0 ? '€${trade.actualEntryPrice.toStringAsFixed(2)}' : (trade.entryPrice > 0 ? '€${trade.entryPrice.toStringAsFixed(2)}' : '-'), Colors.white, ), _priceItem('Live-Kurs', '€${currPrice.toStringAsFixed(2)}', AppTheme.accentCyan), _priceItem( trade.driftStatus == DriftStatus.trailingActive ? 'Stop (Trailing)' : 'Stop-Loss', '€${trade.stopLoss.toStringAsFixed(2)}', AppTheme.accentRed, ), _priceItem( trade.takeProfitTargets.length > 1 ? 'TP (Aktuell)' : 'Take-Profit', '€${trade.takeProfit.toStringAsFixed(2)}', AppTheme.primaryEmerald, ), ], ), ), if (trade.takeProfitTargets.length > 1) ...[ const SizedBox(height: 8), Row( children: [ Text( 'Ziele: ', style: TextStyle(color: AppTheme.textMuted, fontSize: 11, fontWeight: FontWeight.bold), ), Expanded( child: Wrap( spacing: 6, runSpacing: 4, children: trade.takeProfitTargets.asMap().entries.map((entry) { final idx = entry.key; final tpVal = entry.value; final isCurrent = (trade.takeProfit - tpVal).abs() < 0.01; return Container( padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2), decoration: BoxDecoration( color: isCurrent ? AppTheme.primaryEmerald.withValues(alpha: 0.2) : Colors.white.withValues(alpha: 0.05), borderRadius: BorderRadius.circular(6), border: Border.all( color: isCurrent ? AppTheme.primaryEmerald : Colors.white.withValues(alpha: 0.15), ), ), child: Text( 'TP${idx + 1}: €${tpVal.toStringAsFixed(2)}', style: TextStyle( color: isCurrent ? AppTheme.primaryEmerald : Colors.white70, fontSize: 10.5, fontWeight: isCurrent ? FontWeight.w900 : FontWeight.bold, ), ), ); }).toList(), ), ), ], ), ], if (trade.reasoning.isNotEmpty) ...[ const SizedBox(height: 10), Text( trade.reasoning, style: TextStyle(color: AppTheme.textMuted, fontSize: 12), maxLines: 2, overflow: TextOverflow.ellipsis, ), ], // KI-Timeline Expansion if updates exist if (trade.hourlyUpdates.isNotEmpty) ...[ const SizedBox(height: 8), ExpansionTile( tilePadding: EdgeInsets.zero, childrenPadding: const EdgeInsets.only(bottom: 6), dense: true, leading: Icon(Icons.history_toggle_off, color: AppTheme.accentCyan, size: 18), title: Text( 'KI-Guardian Verlauf (${trade.hourlyUpdates.length} Prüfungen)', style: TextStyle(color: AppTheme.accentCyan, fontSize: 12, fontWeight: FontWeight.bold), ), children: trade.hourlyUpdates.reversed.take(4).map((u) { return Container( margin: const EdgeInsets.only(bottom: 6), padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.white.withValues(alpha: 0.03), borderRadius: BorderRadius.circular(6), ), child: Row( children: [ Text( '${u.timestamp.hour.toString().padLeft(2, '0')}:${u.timestamp.minute.toString().padLeft(2, '0')}', style: TextStyle(color: AppTheme.textMuted, fontSize: 11, fontWeight: FontWeight.bold), ), const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: (u.recommendation.toLowerCase().contains('close') ? AppTheme.accentRed : (u.recommendation.toLowerCase().contains('adjust') ? Colors.blue : AppTheme.primaryEmerald)) .withValues(alpha: 0.15), borderRadius: BorderRadius.circular(4), ), child: Text(u.recommendation, style: const TextStyle(color: Colors.white70, fontSize: 10, fontWeight: FontWeight.bold)), ), const SizedBox(width: 8), Expanded( child: Text( u.reasoning.isNotEmpty ? u.reasoning : 'Kurs: €${u.currentPrice.toStringAsFixed(2)} | VIX: ${u.vixValue.toStringAsFixed(1)}', style: TextStyle(color: AppTheme.textMuted, fontSize: 11), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ); }).toList(), ), ], const SizedBox(height: 8), // Collapsible Live-Kalkulation & TP-Multi-Target Card TradeCalculationCard(trade: trade, isCollapsible: true, initiallyExpanded: false), const SizedBox(height: 12), // Footer Action Row Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '${trade.timeframe.isNotEmpty ? trade.timeframe : "1D"}${trade.leverageUsed > 1 ? " • ${trade.leverageUsed.toStringAsFixed(1)}x Hebel" : ""}', style: TextStyle(color: AppTheme.textMuted, fontSize: 11), ), Row( children: [ IconButton( onPressed: () => TradeDetailModal.show( context, trade: trade, onAccept: onAccept, onClose: onClose, ), icon: Icon(Icons.info_outline, size: 18, color: AppTheme.accentCyan), tooltip: 'KI-Begründung & Details', ), if (isProposed && onAccept != null) ...[ const SizedBox(width: 6), ElevatedButton.icon( onPressed: onAccept, icon: const Icon(Icons.check_circle_outline, size: 16), label: const Text('Trade Übernehmen'), style: ElevatedButton.styleFrom( backgroundColor: AppTheme.primaryEmerald, foregroundColor: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), ), ], if (isActive && onClose != null) ...[ const SizedBox(width: 6), OutlinedButton.icon( onPressed: onClose, icon: Icon(Icons.flag_outlined, size: 14, color: AppTheme.accentRed), label: Text('Position Schließen', style: TextStyle(color: AppTheme.accentRed, fontSize: 12, fontWeight: FontWeight.bold)), style: OutlinedButton.styleFrom( side: BorderSide(color: AppTheme.accentRed.withValues(alpha: 0.5)), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), ), ], if (isActive && onSettings != null) ...[ const SizedBox(width: 6), IconButton( onPressed: onSettings, icon: const Icon(Icons.settings, size: 16, color: Colors.white), tooltip: 'Einstellungen anpassen', style: IconButton.styleFrom( backgroundColor: AppTheme.glassSurface, ), ), ], ], ), ], ), ], ), ); }, ); } Widget _buildDriftRadarBar(TradeModel t) { Color col; String label; IconData icon; switch (t.driftStatus) { case DriftStatus.exitAlert: col = AppTheme.accentRed; label = 'Drift-Radar: Ausstieg empfohlen'; icon = Icons.warning_rounded; break; case DriftStatus.trailingActive: col = AppTheme.accentCyan; label = 'Drift-Radar: Trailing-Stop aktiv nachgezogen'; icon = Icons.security; break; case DriftStatus.driftWarning: col = Colors.orangeAccent; label = 'Drift-Radar: Leichte Abweichung von Prognose'; icon = Icons.tune; break; case DriftStatus.onTrack: col = AppTheme.primaryEmerald; label = 'Drift-Radar: Prognose intakt • KI überwacht stündlich'; icon = Icons.radar; break; } return Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), decoration: BoxDecoration( color: col.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(8), border: Border.all(color: col.withValues(alpha: 0.25)), ), child: Row( children: [ Icon(icon, color: col, size: 14), const SizedBox(width: 6), Expanded( child: Text(label, style: TextStyle(color: col, fontSize: 11, fontWeight: FontWeight.bold)), ), ], ), ); } Widget _priceItem(String label, String val, Color valColor) { return Column( children: [ Text(label, style: TextStyle(color: AppTheme.textMuted, fontSize: 10)), const SizedBox(height: 2), Text(val, style: TextStyle(color: valColor, fontWeight: FontWeight.bold, fontSize: 12)), ], ); } }