from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
    QPushButton, QLabel, QLineEdit, QFrame)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont
import pyqtgraph as pg
import numpy as np
import torch
import logging
from datetime import datetime
import asyncio
import time
from typing import Dict, List

class QuantumChart(pg.PlotWidget):
    def __init__(self, title: str, y_label: str, color: str = 'c'):
        super().__init__()
        self.setup_chart(title, y_label, color)

    def setup_chart(self, title: str, y_label: str, color: str):
        self.showGrid(x=True, y=True, alpha=0.2)
        self.setBackground('k')
        
        for axis in [self.getAxis('bottom'), self.getAxis('left')]:
            axis.setPen(pg.mkPen('w'))
            axis.setTextPen(pg.mkPen('w'))
        
        self.getAxis('bottom').setStyle(showValues=True)
        self.getAxis('bottom').setLabel('Time')
        self.getAxis('bottom').setRotation(45)
        
        font = QFont()
        font.setPixelSize(12)
        self.getAxis('bottom').setTickFont(font)
        self.getAxis('left').setTickFont(font)
        
        self.setLabel('left', y_label, color=color)
        self.setTitle(title, color='w')
        
        self.main_line = self.plot(pen=pg.mkPen(color, width=2))
        self.buy_markers = pg.ScatterPlotItem(pen='g', brush='g', symbol='t', size=15)
        self.sell_markers = pg.ScatterPlotItem(pen='r', brush='r', symbol='t1', size=15)
        self.beam_line = self.plot(pen=pg.mkPen('g', width=1))
        
        self.addItem(self.buy_markers)
        self.addItem(self.sell_markers)
        self.beam_data = []
        
        logging.info("QuantumChart initialized successfully.")

class QuantumGUI(QMainWindow):
    def __init__(self, config: Dict, trader, market_signals, scanner):
        super().__init__()
        self.logger = logging.getLogger(__name__)
        self.logger.info("🚀 Initializing Quantum GUI...")
        
        self.config = config
        self.trader = trader
        self.market_signals = market_signals
        self.scanner = scanner
        self.neural_engine = scanner
        
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        if torch.cuda.is_available():
            self.stream = torch.cuda.Stream()
            self.logger.info("CUDA enabled for GUI.")
        
        self.trading_stats = {'wins': 0, 'losses': 0, 'total_pnl': 0.0, 'trades': 0}
        self.price_history = []
        self.volume_history = []
        self.time_labels = []
        self.trade_markers = []
        self.max_points = 100
        self.last_update = 0
        self.update_interval = 0.1
        
        self.buy_btn = None
        self.sell_btn = None
        self.auto_btn = None
        self.size_input = None
        self.price_chart = None
        self.volume_chart = None
        self.balance_label = None
        self.status_label = None
        self.neural_status = None
        
        self.init_ui()
        self.setup_timers()
        self.connect_signals()
        
        if self.config['trading'].get('enabled', True):
            self.auto_btn.setChecked(True)
            asyncio.create_task(self._auto_trading_loop())
        
        self.logger.info("✨ Quantum GUI Ready")

    def init_ui(self):
        self.setWindowTitle("⚡ Quantum Trading Interface")
        self.setStyleSheet("""
            QMainWindow { background: black; }
            QLabel { color: #00ff00; font-family: 'Consolas'; font-size: 12px; padding: 2px; }
            QPushButton { background: #001a00; color: #00ff00; border: 1px solid #00ff00; padding: 5px; font-weight: bold; min-width: 80px; border-radius: 3px; }
            QPushButton:hover { background: #002200; }
            QLineEdit { background: #001a00; color: #00ff00; border: 1px solid #00ff00; padding: 5px; border-radius: 3px; }
            QFrame { border: 1px solid #003300; background: #001100; padding: 5px; border-radius: 5px; }
        """)

        central = QWidget()
        self.setCentralWidget(central)
        layout = QHBoxLayout(central)

        self.init_left_panel(layout)
        self.init_center_panel(layout)
        self.init_right_panel(layout)

        self.setMinimumSize(1200, 800)
        self.show()

    def init_left_panel(self, parent_layout):
        panel = QFrame()
        layout = QVBoxLayout(panel)

        # Wallet info
        wallet_frame = QFrame()
        wallet_layout = QVBoxLayout(wallet_frame)
        self.balance_label = QLabel("Balance: Loading...")
        self.balance_label.setStyleSheet("font-size: 14px; font-weight: bold;")
        self.wallet_label = QLabel("Wallet: " + self.trader.get_wallet_address()[:8] + "...")
        wallet_layout.addWidget(self.balance_label)
        wallet_layout.addWidget(self.wallet_label)
        layout.addWidget(wallet_frame)

        # Trading controls
        controls_frame = QFrame()
        controls_layout = QVBoxLayout(controls_frame)

        size_layout = QHBoxLayout()
        size_layout.addWidget(QLabel("Size (SOL):"))
        self.size_input = QLineEdit()
        self.size_input.setText(str(self.config['trading']['initial_size']))
        size_layout.addWidget(self.size_input)
        controls_layout.addLayout(size_layout)

        button_layout = QHBoxLayout()
        self.buy_btn = QPushButton("BUY")
        self.buy_btn.setStyleSheet("background: #002200; border: 2px solid #00ff00;")
        self.sell_btn = QPushButton("SELL")
        self.sell_btn.setStyleSheet("background: #220000; border: 2px solid #ff0000;")
        button_layout.addWidget(self.buy_btn)
        button_layout.addWidget(self.sell_btn)
        controls_layout.addLayout(button_layout)

        layout.addWidget(controls_frame)
        self.logger.info("Trading controls initialized successfully.")

        # Performance metrics
        metrics_frame = QFrame()
        metrics_layout = QVBoxLayout(metrics_frame)
        metrics_layout.addWidget(QLabel("Performance Metrics"))
        self.win_rate_label = QLabel("Win Rate: 0.00%")
        self.pnl_label = QLabel("Total PNL: 0.00 SOL")
        self.trades_label = QLabel("Total Trades: 0")
        for label in [self.win_rate_label, self.pnl_label, self.trades_label]:
            metrics_layout.addWidget(label)
        layout.addWidget(metrics_frame)

        parent_layout.addWidget(panel, stretch=1)
        self.logger.info("Left panel initialized successfully.")

    def update_data(self):
        """Update market data display"""
        try:
            current_time = time.time()
            if current_time - self.last_update < self.update_interval:
                return

            if torch.cuda.is_available():
            with torch.cuda.stream(self.stream):
                self._update_charts()
        else:
            self._update_charts()

        self.last_update = current_time
    except Exception as e:
        self.logger.error(f"Data update error: {e}")

def update_price(self, price: float):
    """Handle price updates"""
    timestamp = datetime.now().strftime("%H:%M:%S")
    self.time_labels.append(timestamp)
    self.price_history.append(price)
    
    if len(self.price_history) > self.max_points:
        self.price_history = self.price_history[-self.max_points:]
        self.time_labels = self.time_labels[-self.max_points:]

def update_volume(self, volume: float):
    """Handle volume updates"""
    self.volume_history.append(volume)
    if len(self.volume_history) > self.max_points:
        self.volume_history = self.volume_history[-self.max_points:]

def update_connection(self, connected: bool):
    """Update connection status display"""
    self.connection_label.setText(f"{'🟢' if connected else '🔴'} Connection")

def update_neural_metrics(self, data: Dict):
    """Update neural metrics display"""
    try:
        self.neural_status.setText(f"ML Confidence: {data.get('confidence', 0):.2f}%")
    except Exception as e:
        self.logger.error(f"Neural metrics update error: {e}")

def _update_charts(self):
    """Update chart displays"""
    try:
        if self.price_history:
            self.price_chart.update_data(self.price_history, self.time_labels, self.trade_markers)
        if self.volume_history:
            self.volume_chart.update_data(self.volume_history, self.time_labels)
    except Exception as e:
        self.logger.error(f"Chart update error: {e}")

    def init_center_panel(self, parent_layout):
        panel = QFrame()
        layout = QVBoxLayout(panel)

        self.price_chart = QuantumChart("Quantum Price Action", "Price (SOL)")
        layout.addWidget(self.price_chart, stretch=3)

        self.volume_chart = QuantumChart("Volume Profile", "Volume", color='b')
        layout.addWidget(self.volume_chart, stretch=1)

        status_frame = QFrame()
        status_layout = QHBoxLayout(status_frame)
        self.status_label = QLabel("System Ready")
        self.connection_label = QLabel("⚪ Connecting...")
        status_layout.addWidget(self.status_label)
        status_layout.addWidget(self.connection_label)
        layout.addWidget(status_frame)

        parent_layout.addWidget(panel, stretch=2)
        self.logger.info("Center panel initialized successfully.")

    def init_right_panel(self, parent_layout):
        panel = QFrame()
        layout = QVBoxLayout(panel)

        auto_frame = QFrame()
        auto_layout = QVBoxLayout(auto_frame)
        self.auto_btn = QPushButton("Auto Trading: OFF")
        self.auto_btn.setCheckable(True)
        self.auto_btn.setStyleSheet("""
            QPushButton {
                background: #001100;
                border: 2px solid #00ff00;
                padding: 10px;
                font-size: 13px;
            }
            QPushButton:checked { background: #003300; }
        """)
        auto_layout.addWidget(self.auto_btn)
        layout.addWidget(auto_frame)

        parent_layout.addWidget(panel, stretch=1)
        self.logger.info("Right panel initialized successfully.")

    async def start(self):
        self.logger.info("🚀 Starting Quantum GUI...")
        try:
            await self.market_signals.start()
            await self.scanner.initialize()
            self.status_label.setText("System ready")
            self.logger.info("GUI started successfully")
        except Exception as e:
            self.logger.error(f"Startup error: {e}")
            self.status_label.setText("Startup error")
            raise

    def setup_timers(self):
        self.market_timer = QTimer()
        self.market_timer.timeout.connect(self.update_data)
        self.market_timer.start(50)

        self.balance_timer = QTimer()
        self.balance_timer.timeout.connect(lambda: asyncio.create_task(self.update_balance()))
        self.balance_timer.start(5000)

    def connect_signals(self):
        if self.buy_btn and self.sell_btn:
            self.buy_btn.clicked.connect(lambda: asyncio.create_task(self.execute_trade('buy')))
            self.sell_btn.clicked.connect(lambda: asyncio.create_task(self.execute_trade('sell')))
        
        if self.auto_btn:
            self.auto_btn.toggled.connect(self.toggle_auto_trading)
        
        if hasattr(self.market_signals, 'signals'):
            self.market_signals.signals.price_update.connect(self.update_price)
            self.market_signals.signals.volume_update.connect(self.update_volume)
            self.market_signals.signals.connection_update.connect(self.update_connection)

        if hasattr(self.scanner, 'signals'):
            self.scanner.signals.prediction_update.connect(self.update_neural_metrics)

    async def cleanup(self):
        self.logger.info("Cleaning up GUI resources...")
        try:
            if self.market_timer:
                self.market_timer.stop()
            if self.balance_timer:
                self.balance_timer.stop()
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
            await self.trader.cleanup()
            self.logger.info("GUI cleanup completed successfully.")
        except Exception as e:
            self.logger.error(f"Cleanup error: {e}")
 fix spacing and put logging please