"""
Base dialog class with common patterns and utilities
"""

from ..qt_compat import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QTextEdit,
    QDialogButtonBox, QMessageBox, QGroupBox, QFormLayout
)
from ..qt_compat import Qt
from typing import Optional
from ..onboarding_ui import create_hint_panel


class BaseDialog(QDialog):
    """Base class for EMDS dialogs with common patterns"""

    def __init__(self, title: str, parent=None, width: int = 500, height: int = 400):
        """
        Initialize base dialog

        Args:
            title: Dialog window title
            parent: Parent widget
            width: Dialog width
            height: Dialog height
        """
        super().__init__(parent)
        self.setWindowTitle(title)
        self.setGeometry(100, 100, width, height)

    def create_main_layout(self) -> QVBoxLayout:
        """Create and set main vertical layout"""
        layout = QVBoxLayout()
        self.setLayout(layout)
        return layout

    def add_text_field(self, layout: QVBoxLayout, label: str, is_multiline: bool = False) -> QLineEdit or QTextEdit:
        """
        Add a text input field to layout

        Args:
            layout: Parent layout
            label: Field label
            is_multiline: If True, creates QTextEdit; otherwise QLineEdit

        Returns:
            QLineEdit or QTextEdit widget
        """
        label_widget = QLabel(label)
        layout.addWidget(label_widget)
        if is_multiline:
            widget = QTextEdit()
            widget.setMaximumHeight(100)
        else:
            widget = QLineEdit()
        widget._field_label = label_widget
        layout.addWidget(widget)
        return widget

    def add_rich_text_field(self, layout: QVBoxLayout, label: str, stretch: int = 1):
        """Add a growable rich-text comments editor (Q6b) to the layout.

        Drop-in upgrade for ``add_text_field(is_multiline=True)`` — the
        returned :class:`RichCommentEditor` answers ``toPlainText`` /
        ``setPlainText`` like a QTextEdit, and additionally exposes
        ``html()`` for the ``emds_comments_html`` metadata sidecar.
        """
        from ..rich_comment_editor import RichCommentEditor

        label_widget = QLabel(label)
        layout.addWidget(label_widget)
        widget = RichCommentEditor(self)
        widget._field_label = label_widget
        # Growable: the editor absorbs extra dialog height instead of
        # being pinned to a 100 px box.
        layout.addWidget(widget, stretch)
        return widget

    def add_form_group(self, layout: QVBoxLayout, title: str):
        """
        Add a grouped section with form layout.

        Returns:
            Tuple of (QGroupBox, QFormLayout). Existing callers that only need
            the form layout can use the second element; new callers that need
            to retranslate the group title can use the first.
        """
        group = QGroupBox(title)
        form_layout = QFormLayout()
        group.setLayout(form_layout)
        layout.addWidget(group)
        return group, form_layout

    def add_hint_panel(
        self,
        layout: QVBoxLayout,
        title: str,
        body: str,
        link_key: Optional[str] = None,
        link_text: str = "Watch this step",
    ):
        """Add a reusable onboarding hint panel to the layout."""
        panel = create_hint_panel(
            title=title,
            body=body,
            link_key=link_key,
            link_text=link_text,
            parent=self,
        )
        layout.addWidget(panel)
        return panel

    def add_buttons(self, layout: QVBoxLayout, ok_callback=None, cancel_callback=None) -> QDialogButtonBox:
        """
        Add OK/Cancel buttons

        Args:
            layout: Parent layout
            ok_callback: Optional custom OK handler
            cancel_callback: Optional custom Cancel handler

        Returns:
            QDialogButtonBox
        """
        button_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        if ok_callback:
            button_box.accepted.connect(ok_callback)
        else:
            button_box.accepted.connect(self.accept)

        if cancel_callback:
            button_box.rejected.connect(cancel_callback)
        else:
            button_box.rejected.connect(self.reject)

        layout.addWidget(button_box)
        return button_box

    def validate_required_field(self, widget, field_name: str) -> bool:
        """
        Validate that a required field is not empty

        Args:
            widget: QLineEdit or QTextEdit to validate
            field_name: Name of field for error message

        Returns:
            True if valid, False otherwise
        """
        if isinstance(widget, QTextEdit):
            text = widget.toPlainText().strip()
        else:
            text = widget.text().strip()

        if not text:
            QMessageBox.warning(self, "Validation Error", f"Please enter a {field_name}")
            return False
        return True

    def show_error(self, title: str, message: str):
        """Show error message box"""
        QMessageBox.critical(self, title, message)

    def show_warning(self, title: str, message: str):
        """Show warning message box"""
        QMessageBox.warning(self, title, message)

    def show_info(self, title: str, message: str):
        """Show info message box"""
        QMessageBox.information(self, title, message)

    def show_confirmation(self, title: str, message: str) -> bool:
        """Show confirmation dialog, return True if user clicked Yes"""
        reply = QMessageBox.question(
            self,
            title,
            message,
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        return reply == QMessageBox.StandardButton.Yes
