from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QTextEdit, QPushButton, QWidget
from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt
from PySide6.QtSvgWidgets import QSvgWidget
from src.path_resolver import PathResolver


def build_layout(self):
    """
    The main layout for displaying tool details.
    Keeps the modern structure but uses theme-inherited colors.
    """
    main_v_layout = QVBoxLayout()
    main_v_layout.setContentsMargins(10, 10, 10, 10)
    main_v_layout.setSpacing(15)

    title_label = QLabel(self.tool["name"], self)
    title_label.setStyleSheet("font-size: 24px; font-weight: bold; color: palette(window-text); margin-bottom: 2px;")
    main_v_layout.addWidget(title_label)
    
    main_v_layout.addSpacing(5)

    details_layout = QHBoxLayout()
    details_layout.setSpacing(20)

    image_layout = image_section(self)
    details_layout.addLayout(image_layout)

    text_info_layout = QVBoxLayout()
    text_info_layout.setSpacing(8)

    tags_layout = QHBoxLayout()
    tags_layout.setSpacing(10)

    version_tag = QLabel(f"Version: {self.tool['version']}", self)
    version_tag.setStyleSheet("""
        padding: 3px 10px; 
        border-radius: 8px; 
        border: 1px solid palette(mid);
        background-color: palette(alternate-base);
        color: palette(window-text);
    """)

    size_tag = QLabel(f"Size: {self.tool['size']}", self)
    size_tag.setStyleSheet("""
        padding: 3px 10px; 
        border-radius: 8px; 
        border: 1px solid palette(mid);
        background-color: palette(alternate-base);
        color: palette(window-text);
    """)

    tags_layout.addWidget(version_tag)
    tags_layout.addWidget(size_tag)
    tags_layout.addStretch()

    text_info_layout.addLayout(tags_layout)

    website_label = QLabel(f'Site: <a href="{self.tool["website"]}" style="color: palette(link);">{self.tool["website"]}</a>', self)
    website_label.setTextFormat(Qt.TextFormat.RichText)
    website_label.setOpenExternalLinks(True)
    text_info_layout.addWidget(website_label)

    # Description box - using a fixed color for description results in issues on light themes, 
    # so we use palette(text) and ensure background is transparent.
    description_text = QTextEdit(self.tool["description"], self)
    description_text.setReadOnly(True)
    description_text.setStyleSheet("background: transparent; border: none; color: palette(text); font-size: 13px;")
    # Ensure the description doesn't push the title out
    description_text.setMaximumHeight(100) 
    text_info_layout.addWidget(description_text)

    details_layout.addLayout(text_info_layout, stretch=1)
    main_v_layout.addLayout(details_layout)
    return main_v_layout


def image_section(self):
    # Using a container widget to provide a consistent background and border
    container = QWidget()
    container.setFixedSize(140, 140)
    # alternate-base usually provides a subtle contrast to a base background
    container.setStyleSheet("""
        QWidget {
            background-color: palette(base);
            border: 1px solid palette(mid);
            border-radius: 12px;
        }
    """)
    
    container_layout = QVBoxLayout(container)
    container_layout.setContentsMargins(10, 10, 10, 10)
    
    image_label = QLabel()
    image_path = PathResolver.resource_path(self.tool["image"])

    if self.tool["image"].endswith(".svg"):
        svg_widget = QSvgWidget(image_path)
        svg_widget.setFixedSize(110, 110)
        container_layout.addWidget(svg_widget, alignment=Qt.AlignmentFlag.AlignCenter)
    else:
        pixmap = QPixmap(image_path)
        pixmap = pixmap.scaled(110, 110, Qt.AspectRatioMode.KeepAspectRatio,
                               Qt.TransformationMode.SmoothTransformation)
        image_label.setPixmap(pixmap)
        container_layout.addWidget(image_label, alignment=Qt.AlignmentFlag.AlignCenter)

    # We return a layout containing our container to maintain compatibility
    wrapper_layout = QVBoxLayout()
    wrapper_layout.addWidget(container)
    wrapper_layout.addStretch()
    return wrapper_layout


def usage_examples_section(self, layout):
    """
    Displays CLI usage examples with a clean, themed look.
    """
    examples_label = QLabel("USAGE EXAMPLES", self)
    examples_label.setStyleSheet("font-size: 11px; font-weight: bold; opacity: 0.7; margin-top: 10px;")
    layout.addWidget(examples_label)

    examples_text = QTextEdit(self)
    examples_text.setReadOnly(True)
    # Using palette colors ensures visibility on both dark and light themes
    examples_text.setStyleSheet("""
         background-color: palette(base);
         color: palette(text);
         font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
         border: 1px solid palette(mid);
         border-radius: 8px;
         padding: 8px;
     """)
    examples_text.setPlainText("\n\n".join(self.tool["examples"]))
    layout.addWidget(examples_text)


def container_buttons_section(self, layout):
    """
    Control buttons section.
    """
    buttons_layout = QHBoxLayout()
    buttons_layout.setContentsMargins(0, 10, 0, 0)
    
    self.run_button = QPushButton('RUN CONTAINER', self)
    self.run_button.setCursor(Qt.CursorShape.PointingHandCursor)
    self.run_button.setMinimumHeight(45) # Keep increased height
    
    self.stop_button = QPushButton('STOP', self)
    self.stop_button.setCursor(Qt.CursorShape.PointingHandCursor)
    self.stop_button.setMinimumHeight(45) # Keep increased height
    
    buttons_layout.addWidget(self.run_button, stretch=2)
    buttons_layout.addWidget(self.stop_button, stretch=1)
    layout.addLayout(buttons_layout)

    self.dockerfile_button = QPushButton('Generate Dockerfile', self)
    self.dockerfile_button.setCursor(Qt.CursorShape.PointingHandCursor)
    self.dockerfile_button.setMinimumHeight(35)
    layout.addWidget(self.dockerfile_button)
