from __future__ import annotations

import re
from importlib import resources
from pathlib import Path

from PySide6.QtCore import Qt
from PySide6.QtGui import QFont, QTextCursor, QTextDocument
from PySide6.QtWidgets import (
    QDialog,
    QHBoxLayout,
    QLineEdit,
    QPushButton,
    QTextBrowser,
    QVBoxLayout,
)

from .theme import ThemeColors


def load_help_markdown() -> str:
    try:
        return resources.files("pdfimgq.gui").joinpath("help.md").read_text(encoding="utf-8")
    except Exception:
        pass

    try:
        p = Path(__file__).with_name("help.md")
        return p.read_text(encoding="utf-8")
    except Exception:
        return "# Help\n\nHelp content is missing.\n"


def _inject_style_into_html(html: str, css: str) -> str:
    style_tag = f"<style>\n{css}\n</style>\n"
    if "<head>" in html:
        return html.replace("<head>", "<head>\n" + style_tag, 1)
    return f"<!DOCTYPE html><html><head>{style_tag}</head><body>{html}</body></html>"


def markdown_to_styled_html(md: str, base_font: QFont, colors: ThemeColors) -> str:
    doc = QTextDocument()
    doc.setDefaultFont(base_font)
    doc.setMarkdown(md)
    html = doc.toHtml()

    html = re.sub(r'margin-top:\s*\d+px;?', '', html)
    html = re.sub(r'margin-bottom:\s*\d+px;?', '', html)

    css = """
    body {
        margin: 0;
        line-height: 1.28;
        color: %(text)s;
        background: %(window_bg)s;
    }

    h1 { 
        font-size: 1.55em; 
        font-weight: 700; 
        margin-top: 0px; 
        margin-bottom: 10px; 
        color: %(text)s;
    }
    h2 { 
        font-size: 1.32em; 
        font-weight: 700; 
        margin-top: 0px; 
        margin-bottom: 8px; 
        color: %(text)s;
    }
    h3 { 
        font-size: 1.15em; 
        font-weight: 700; 
        margin-top: 24px; 
        margin-bottom: 4px; 
        color: %(text)s;
    }

    p { margin: 0px 0; }

    ul, ol { margin: 8px 0 12px 22px; padding: 0; }
    li { margin: 0px 0; }

    a {
        color: %(link)s;
    }

    hr {
        border: none;
        border-top: 1px solid %(border)s;
        margin: 18px 0;
    }

    blockquote {
        margin: 12px 0;
        padding: 6px 0 6px 12px;
        color: %(muted_text)s;
        border-left: 3px solid %(border_strong)s;
    }

    code {
        font-family: Consolas, "Courier New", monospace;
        background: %(code_bg)s;
        padding: 1px 4px;
        border-radius: 4px;
    }

    pre {
        font-family: Consolas, "Courier New", monospace;
        background: %(code_bg)s;
        padding: 10px 12px;
        border-radius: 6px;
        overflow-x: auto;
        margin: 10px 0;
    }
    """ % {
        "text": colors.text,
        "window_bg": colors.window_bg,
        "link": colors.link,
        "border": colors.border,
        "border_strong": colors.border_strong,
        "muted_text": colors.muted_text,
        "code_bg": colors.code_bg,
    }

    return _inject_style_into_html(html, css)


class HelpDialog(QDialog):
    def __init__(self, theme_colors: ThemeColors, parent=None) -> None:
        super().__init__(parent)
        self.setWindowTitle("Help")
        self.setWindowModality(Qt.WindowModality.NonModal)
        self.resize(980, 760)

        base = self.font()
        base.setPointSize(11)
        self.setFont(base)
        self._theme_colors = theme_colors
        self._markdown = load_help_markdown()

        self.searchEdit = QLineEdit(self)
        self.searchEdit.setPlaceholderText("Search… (Enter = next)")
        self.searchEdit.setFont(base)

        self.nextButton = QPushButton("Next", self)
        self.nextButton.setFont(base)
        self.nextButton.setAutoDefault(False)

        top = QHBoxLayout()
        top.addWidget(self.searchEdit, 1)
        top.addWidget(self.nextButton, 0)

        self.browser = QTextBrowser(self)
        self.browser.setOpenExternalLinks(True)
        self.browser.setReadOnly(True)
        self.browser.setFont(base)

        doc = self.browser.document()
        doc.setDefaultFont(base)
        doc.setDocumentMargin(16)

        layout = QVBoxLayout(self)
        layout.addLayout(top)
        layout.addWidget(self.browser, 1)

        self.searchEdit.returnPressed.connect(self.find_next)
        self.nextButton.clicked.connect(self.find_next)
        self.apply_theme(theme_colors)

    def apply_theme(self, theme_colors: ThemeColors) -> None:
        self._theme_colors = theme_colors
        scroll_pos = self.browser.verticalScrollBar().value()
        html = markdown_to_styled_html(self._markdown, self.font(), theme_colors)
        self.browser.setHtml(html)
        self.browser.verticalScrollBar().setValue(scroll_pos)
        self.browser.setStyleSheet(
            f"""
            QTextBrowser {{
                background: {theme_colors.window_bg};
                color: {theme_colors.text};
                border: 1px solid {theme_colors.border};
                border-radius: 4px;
            }}
            """
        )

    def find_next(self) -> None:
        term = self.searchEdit.text().strip()
        if not term:
            return

        if self.browser.find(term):
            return

        cursor = self.browser.textCursor()
        cursor.movePosition(QTextCursor.MoveOperation.Start)
        self.browser.setTextCursor(cursor)
        self.browser.find(term)
