"""Main window for EuBI-Bridge PyQt6 GUI."""

import logging
from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTabWidget,
    QLabel, QPushButton, QMessageBox
)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon, QPixmap

from eubi_bridge.ebridge import EuBIBridge
from eubi_bridge.gui.state import MainWindowState, AppState
from eubi_bridge.gui.views.channel_editor import VisualChannelEditor
from eubi_bridge.gui.views.metadata_editor import PixelMetadataEditor

logger = logging.getLogger(__name__)


class MainWindow(QMainWindow):
    """Main application window for EuBI-Bridge PyQt6 GUI."""
    
    def __init__(self):
        super().__init__()
        
        self.state = MainWindowState()
        self.app_state = AppState()
        
        # Initialize bridge
        try:
            self.bridge = EuBIBridge()
        except Exception as e:
            logger.error(f"Failed to initialize EuBIBridge: {e}")
            QMessageBox.critical(
                self,
                "Initialization Error",
                f"Failed to initialize EuBI-Bridge: {e}\n\n"
                "Please ensure all dependencies are installed."
            )
            self.bridge = None
        
        self._setup_ui()
        self._apply_stylesheet()
    
    def _setup_ui(self):
        """Build main UI."""
        self.setWindowTitle("EuBI-Bridge - PyQt6 GUI")
        self.setWindowIcon(self._create_window_icon())
        self.setMinimumSize(QSize(1400, 900))
        
        # Central widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(5, 5, 5, 5)
        
        # Header
        layout.addWidget(self._create_header())
        
        # Tab widget for views
        self.tabs = QTabWidget()
        
        # Create views
        if self.bridge:
            self.channel_editor = VisualChannelEditor(self.bridge)
            self.metadata_editor = PixelMetadataEditor(self.bridge)
            
            self.tabs.addTab(self.channel_editor, "🎨 Channel Editor")
            self.tabs.addTab(self.metadata_editor, "📐 Metadata Editor")
        
        layout.addWidget(self.tabs, 1)
        
        # Status bar
        self.statusBar().showMessage("Ready")
        
        central_widget.setLayout(layout)
    
    def _create_header(self) -> QWidget:
        """Create header with title and info."""
        header = QWidget()
        layout = QHBoxLayout(header)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # Title
        title = QLabel("EuBI-Bridge")
        title.setStyleSheet("font-size: 24px; font-weight: bold; color: #000000;")
        layout.addWidget(title)
        
        # Subtitle
        subtitle = QLabel("OME-Zarr Visualization & Editing")
        subtitle.setStyleSheet("font-size: 12px; color: #333333;")
        layout.addWidget(subtitle)
        
        layout.addStretch()
        
        # Help button
        help_btn = QPushButton("?")
        help_btn.setMaximumWidth(30)
        help_btn.clicked.connect(self._show_help)
        layout.addWidget(help_btn)
        
        return header
    
    def _create_window_icon(self) -> QIcon:
        """Create window icon (placeholder)."""
        pixmap = QPixmap(64, 64)
        pixmap.fill(Qt.GlobalColor.blue)
        return QIcon(pixmap)
    
    def _apply_stylesheet(self):
        """Apply application stylesheet with high contrast."""
        stylesheet = """
        QMainWindow {
            background-color: #ffffff;
            color: #000000;
        }
        
        QWidget {
            color: #000000;
        }
        
        QLabel {
            color: #000000;
        }
        
        QGroupBox {
            border: 2px solid #333333;
            border-radius: 4px;
            margin-top: 12px;
            padding-top: 10px;
            font-weight: bold;
            color: #000000;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 3px 0 3px;
            color: #000000;
        }
        
        QPushButton {
            background-color: #0066cc;
            color: #ffffff;
            border: 1px solid #004499;
            border-radius: 4px;
            padding: 8px 16px;
            font-weight: bold;
        }
        
        QPushButton:hover {
            background-color: #0052a3;
        }
        
        QPushButton:pressed {
            background-color: #003d7a;
        }
        
        QPushButton:disabled {
            background-color: #cccccc;
            color: #666666;
        }
        
        QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QTextEdit {
            border: 1px solid #666666;
            border-radius: 3px;
            padding: 6px;
            background-color: #ffffff;
            color: #000000;
            selection-background-color: #0066cc;
            selection-color: #ffffff;
        }
        
        QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, 
        QComboBox:focus, QTextEdit:focus {
            border: 2px solid #0066cc;
            outline: none;
        }
        
        QCheckBox, QRadioButton {
            color: #000000;
        }
        
        QSlider::groove:horizontal {
            border: 1px solid #666666;
            height: 8px;
            background: #e8e8e8;
            margin: 2px 0;
            border-radius: 4px;
        }
        
        QSlider::handle:horizontal {
            background: #0066cc;
            border: 2px solid #0052a3;
            width: 14px;
            margin: -3px 0;
            border-radius: 7px;
        }
        
        QSlider::handle:horizontal:hover {
            background: #0052a3;
        }
        
        QTabWidget::pane {
            border: 1px solid #999999;
        }
        
        QTabBar::tab {
            background-color: #d9d9d9;
            color: #000000;
            padding: 8px 20px;
            margin-right: 2px;
            border: 1px solid #999999;
        }
        
        QTabBar::tab:selected {
            background-color: #ffffff;
            color: #000000;
            border-bottom: 3px solid #0066cc;
        }
        
        QTabBar::tab:hover {
            background-color: #e8e8e8;
        }
        
        QTableWidget {
            border: 1px solid #999999;
            gridline-color: #cccccc;
            background-color: #ffffff;
            color: #000000;
        }
        
        QTableWidget QTableCornerButton::section {
            background-color: #d9d9d9;
        }
        
        QHeaderView::section {
            background-color: #d9d9d9;
            color: #000000;
            padding: 4px;
            border: 1px solid #999999;
            font-weight: bold;
        }
        
        QListWidget {
            border: 1px solid #999999;
            background-color: #ffffff;
            color: #000000;
        }
        
        QListWidget::item {
            color: #000000;
        }
        
        QListWidget::item:selected {
            background-color: #0066cc;
            color: #ffffff;
        }
        
        QListWidget::item:hover {
            background-color: #e8f0ff;
        }
        
        QScrollBar:vertical {
            border: none;
            background: #f5f5f5;
            width: 14px;
            margin: 0;
        }
        
        QScrollBar::handle:vertical {
            background: #999999;
            border-radius: 7px;
            min-height: 20px;
        }
        
        QScrollBar::handle:vertical:hover {
            background: #666666;
        }
        
        QScrollBar:horizontal {
            border: none;
            background: #f5f5f5;
            height: 14px;
            margin: 0;
        }
        
        QScrollBar::handle:horizontal {
            background: #999999;
            border-radius: 7px;
            min-width: 20px;
        }
        
        QScrollBar::handle:horizontal:hover {
            background: #666666;
        }
        """
        self.setStyleSheet(stylesheet)
    
    def _show_help(self):
        """Show help dialog."""
        help_text = """
<h2>EuBI-Bridge PyQt6 GUI</h2>

<h3>Channel Editor</h3>
<ul>
    <li><b>File Browser:</b> Browse and select OME-Zarr files from disk</li>
    <li><b>Navigate Image:</b> Use sliders to move through T (time), Z (depth) dimensions</li>
    <li><b>FOV (Field of View):</b> Adjust visible area size (64-1024 pixels)</li>
    <li><b>Orientation:</b> Switch between XY, XZ, YZ planes</li>
    <li><b>Channel Settings:</b> Edit intensity ranges and channel colors</li>
    <li><b>Update Metadata:</b> Save channel labels, colors, and metadata changes</li>
</ul>

<h3>Metadata Editor</h3>
<ul>
    <li><b>Load OME-Zarr:</b> Select and load OME-Zarr file to inspect metadata</li>
    <li><b>Axis Metadata:</b> Edit scale factors and units for each dimension (T, Z, Y, X, C)</li>
    <li><b>Storage Info:</b> View chunk sizes, compression methods, and disk usage</li>
    <li><b>Update Metadata:</b> Apply changes to OME-Zarr file metadata</li>
</ul>

<h3>Performance Tips</h3>
<ul>
    <li>Large directories are paginated for responsiveness</li>
    <li>Image planes are cached to avoid re-extraction</li>
    <li>Use zoom controls to adjust resolution level</li>
    <li>Lock changes to prevent accidental edits</li>
</ul>

<h3>Keyboard Shortcuts</h3>
<ul>
    <li><b>Ctrl+O:</b> Browse for OME-Zarr file</li>
    <li><b>Ctrl+S:</b> Save metadata changes</li>
    <li><b>Tab:</b> Switch between editors</li>
</ul>
        """
        
        QMessageBox.information(self, "Help", help_text)
    
    def closeEvent(self, event):
        """Handle window close."""
        # Clean up worker threads
        from eubi_bridge.gui.workers import get_worker_pool
        pool = get_worker_pool()
        pool.wait_for_done(timeout_ms=2000)
        event.accept()


def create_main_window() -> MainWindow:
    """Factory function to create main window."""
    return MainWindow()
