"""
Set up the info layout for the main widget.
"""

from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QDialog, QPushButton
from PySide6.QtGui import QIcon, QPixmap
from PySide6.QtCore import QSize, Qt
from src.path_resolver import PathResolver
from src.theme_manager import ThemeManager


class InfoDialog(QDialog):
    """
    Adds an Info button with an icon to the layout, sets its tooltip, and connects it to
    the show_info function. Also, adds the Docker status label and its icon to the layout.
    """

    WINDOW_SIZE = (400, 500)
    BUTTON_SIZE = (35, 35)
    ICON_SIZE = (20, 20)
    LOGO_SIZE = (100, 100)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.theme_manager = ThemeManager()
        self._setup_dialog()
        self._create_layout()

    def _setup_dialog(self):
        self.setWindowTitle('Info')
        self.setFixedSize(self.WINDOW_SIZE[0], self.WINDOW_SIZE[1])

    def _create_layout(self):
        layout = QVBoxLayout()

        self._add_logo(layout)
        layout.addWidget(self._create_info_text())
        layout.addLayout(self._create_button_layout())

        self.setLayout(layout)

    def _add_logo(self, layout: QVBoxLayout):
        logo_label = QLabel()
        logo_path = PathResolver.resource_path('resources/assets/rocket.svg')
        logo_pixmap = QPixmap(logo_path)

        if logo_pixmap.isNull():
            print("Warning: Rocket logo file not found.")
            return

        scaled_pixmap = logo_pixmap.scaled(
            self.LOGO_SIZE[0], self.LOGO_SIZE[1],
            Qt.AspectRatioMode.KeepAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )
        logo_label.setPixmap(scaled_pixmap)
        logo_label.setFixedSize(self.LOGO_SIZE[0], self.LOGO_SIZE[1])

        logo_layout = QHBoxLayout()
        logo_layout.addStretch()
        logo_layout.addWidget(logo_label)
        logo_layout.addStretch()

        layout.addLayout(logo_layout)

    def _create_info_text(self) -> QLabel:
        check_icon = PathResolver.resource_path('resources/assets/check.png')
        cross_icon = PathResolver.resource_path('resources/assets/cross.png')

        info_text = QLabel()
        info_text.setWordWrap(True)
        info_text.setOpenExternalLinks(True)

        content = self._get_info_content(check_icon, cross_icon)
        info_text.setText(content)

        return info_text

    @staticmethod
    def _get_info_content(check_icon: str, cross_icon: str) -> str:
        """
        Generate the info content for the dialog.
        """
        return (
            '<div style="text-align: center; font-family: sans-serif;">'
            '<h2 style="margin-bottom: 5px;">Rocket</h2>'
            '<p style="opacity: 0.8; margin-bottom: 15px;">Containerized Security Tools Launcher</p>'
            '<p style="font-size: 13px; margin-bottom: 20px; line-height: 1.4;">'
            'Simply select a tool, configure options, and launch.<br>'
            'Rocket handles the Docker container lifecycle for you.'
            '</p>'

            '<b>Version 1.5.1</b><br><br>'
            f'<img src="{check_icon}" width="14" height="14" style="vertical-align: middle;"/> <span style="vertical-align: middle;">Image Ready</span> &nbsp;&nbsp;&nbsp;'
            f'<img src="{cross_icon}" width="14" height="14" style="vertical-align: middle;"/> <span style="vertical-align: middle;">Image Missing</span>'
            '<br>'
            '<div style="margin-top: 5px; margin-bottom: 10px;">'
            '<a href="https://gitlab.com/parrotsec/project/rocket" style="text-decoration: none; font-weight: bold;">GitLab Source</a>'
            '</div>'
            '<span style="font-size: 11px; opacity: 0.6;">'
            'Maintained by <a href="mailto:danterolle@parrotsec.org">Dario Camonita</a><br>'
            'ParrotSec Team &copy; 2026<br>'
            'Released under <a href="https://www.gnu.org/licenses/gpl-3.0-standalone.html">GPLv3</a>'
            '</span>'
            '</div>'
        )

    def _create_button_layout(self) -> QHBoxLayout:
        layout = QHBoxLayout()

        theme_button = QPushButton('Change Theme')
        # Do not use parentheses when linking a method
        # if you do not want it to be executed immediately.
        theme_button.clicked.connect(self.theme_manager.show_theme_selector)
        # The method will only be invoked when the button is clicked.

        close_button = QPushButton('Close')
        close_button.clicked.connect(self.accept)

        layout.addWidget(theme_button)
        layout.addWidget(close_button)

        return layout

    @classmethod
    def create_info_button(cls) -> QPushButton:
        """
        Set up the Info button with an icon and tooltip.
        """
        button = QPushButton()
        button.setFixedSize(cls.BUTTON_SIZE[0], cls.BUTTON_SIZE[1])
        button.setToolTip('Show Rocket information')

        icon_path = PathResolver.resource_path('resources/assets/info.png')
        button.setIcon(QIcon(icon_path))
        button.setIconSize(QSize(cls.ICON_SIZE[0], cls.ICON_SIZE[1]))

        # No transparency, use theme colors
        button.setStyleSheet("""
            QPushButton {
                border-radius: 6px;
            }
        """)

        # Each time the button is pressed, a new class object is created using cls()
        # exec() opens the dialogue in modal mode, which blocks interaction with
        # other parts of the interface until it is closed.
        button.clicked.connect(lambda: cls().exec())

        return button

    @staticmethod
    def create_info_layout(main_widget, main_layout) -> None:
        """
        Integrate information controls into the main interface.
        """
        info_layout = QHBoxLayout()

        info_button = InfoDialog.create_info_button()

        info_layout.addWidget(info_button)
        info_layout.addStretch()
        info_layout.addWidget(main_widget.ui.docker_status_label)
        info_layout.addWidget(main_widget.ui.docker_status_icon)

        main_layout.addLayout(info_layout)
