"""
SI UI Library - Base Application Window
Provides the standard 3-panel layout (left / centre / right) used by SI tools.

Usage:
    from si_ui import SIBaseApp, SI_DARK_STYLE

    class MyApp(SIBaseApp):
        def create_left_panel(self)   -> QWidget: ...
        def create_center_panel(self) -> QWidget: ...
        def create_right_panel(self)  -> QWidget: ...

    window = MyApp(title="My Tool", min_size=(1000, 550))
    window.setStyleSheet(SI_DARK_STYLE)
    window.show()
"""

from datetime import datetime

from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QHBoxLayout, QVBoxLayout,
    QFrame, QLabel, QTextEdit, QGroupBox,
)

from .theme import SI_DARK_STYLE


class SIBaseApp(QMainWindow):
    """Three-panel dark-themed main window.

    Subclass this and override :meth:`create_left_panel`,
    :meth:`create_center_panel`, and :meth:`create_right_panel`
    to provide your own content.

    Parameters
    ----------
    title : str
        Window title.
    min_size : tuple[int, int]
        (width, height) minimum window size.
    default_size : tuple[int, int]
        (width, height) initial window size.
    left_width : int or None
        Fixed pixel width for the left panel.  *None* = flexible.
    right_width : int or None
        Fixed pixel width for the right panel.  *None* = flexible.
    """

    def __init__(
        self,
        title: str = "SI Application",
        min_size: tuple[int, int] = (1000, 550),
        default_size: tuple[int, int] = (1100, 600),
        left_width: int | None = 260,
        right_width: int | None = 240,
    ):
        super().__init__()
        self._left_width = left_width
        self._right_width = right_width

        self.setWindowTitle(title)
        self.setMinimumSize(*min_size)
        self.resize(*default_size)
        self.setStyleSheet(SI_DARK_STYLE)

        self._build_layout()

    # ------------------------------------------------------------------ #
    # Layout
    # ------------------------------------------------------------------ #
    def _build_layout(self):
        central = QWidget()
        self.setCentralWidget(central)
        main_layout = QHBoxLayout(central)
        main_layout.setContentsMargins(12, 12, 12, 12)
        main_layout.setSpacing(12)

        left = self.create_left_panel()
        if self._left_width is not None:
            left.setFixedWidth(self._left_width)
        main_layout.addWidget(left)

        center = self.create_center_panel()
        main_layout.addWidget(center, stretch=2)

        right = self.create_right_panel()
        if self._right_width is not None:
            right.setFixedWidth(self._right_width)
        main_layout.addWidget(right)

    # ------------------------------------------------------------------ #
    # Override these in subclasses
    # ------------------------------------------------------------------ #
    def create_left_panel(self) -> QWidget:
        """Return the left-side panel widget.  Override in subclass."""
        return self._placeholder_panel("Left Panel")

    def create_center_panel(self) -> QWidget:
        """Return the centre panel widget.  Override in subclass."""
        return self._placeholder_panel("Center Panel")

    def create_right_panel(self) -> QWidget:
        """Return the right-side panel widget.  Override in subclass."""
        return self._placeholder_panel("Right Panel")

    # ------------------------------------------------------------------ #
    # Convenience helpers available to all subclasses
    # ------------------------------------------------------------------ #
    @staticmethod
    def make_panel() -> tuple[QFrame, QVBoxLayout]:
        """Create a styled dark panel frame and its layout."""
        panel = QFrame()
        panel.setObjectName("panel")
        layout = QVBoxLayout(panel)
        layout.setContentsMargins(12, 12, 12, 12)
        layout.setSpacing(8)
        return panel, layout

    @staticmethod
    def make_separator() -> QFrame:
        """Horizontal 1 px separator line."""
        sep = QFrame()
        sep.setObjectName("separator")
        return sep

    @staticmethod
    def make_title(text: str) -> QLabel:
        """Primary title label (blue, bold, 14 px)."""
        lbl = QLabel(text)
        lbl.setObjectName("titleLabel")
        return lbl

    @staticmethod
    def make_subtitle(text: str) -> QLabel:
        """Secondary subtitle label (grey, 8 px, letter-spaced)."""
        lbl = QLabel(text)
        lbl.setObjectName("subtitleLabel")
        return lbl

    @staticmethod
    def make_group(title: str) -> tuple[QGroupBox, QVBoxLayout]:
        """Styled group box with a vertical layout."""
        group = QGroupBox(title)
        layout = QVBoxLayout(group)
        layout.setContentsMargins(8, 12, 8, 8)
        layout.setSpacing(4)
        return group, layout

    @staticmethod
    def make_log_widget(max_height: int = 100) -> QTextEdit:
        """Read-only log text area."""
        log = QTextEdit()
        log.setReadOnly(True)
        log.setMaximumHeight(max_height)
        return log

    @staticmethod
    def log_message(log_widget: QTextEdit, msg: str):
        """Append a timestamped message to a log QTextEdit."""
        ts = datetime.now().strftime("%H:%M:%S")
        log_widget.append(f"[{ts}] {msg}")

    # ------------------------------------------------------------------ #
    # Internal
    # ------------------------------------------------------------------ #
    def _placeholder_panel(self, text: str) -> QWidget:
        panel, layout = self.make_panel()
        layout.addWidget(QLabel(text))
        layout.addStretch()
        return panel
