# -*- coding: utf-8 -*-
"""Reusable view widgets and style helpers."""

from util.runtime import *
from util.utils import _server_id_sort_key

class ServerIdTableItem(QTableWidgetItem):
    """按服务器 ID 数值排序的表格项。"""

    def __init__(self, status_icon: str, server_id):
        self.server_id = str(server_id or "").strip()
        self._sort_key = _server_id_sort_key(self.server_id)
        super().__init__(f"{status_icon} {self.server_id}")

    def __lt__(self, other):
        if isinstance(other, ServerIdTableItem):
            return self._sort_key < other._sort_key
        return super().__lt__(other)


class NoWheelSpinBox(QSpinBox):
    """禁用滚轮改变数值；accept 事件以免滚轮穿透到外层滚动区域。"""
    def wheelEvent(self, event):
        event.accept()


class NoWheelComboBox(QComboBox):
    """禁用滚轮切换项；accept 以免滚轮穿透到外层滚动区域。"""
    def wheelEvent(self, event):
        event.accept()


class NoWheelDateTimeEdit(QDateTimeEdit):
    """禁用滚轮改变开服时间等；accept 以免滚轮穿透到外层滚动区域。"""
    def wheelEvent(self, event):
        event.accept()


_ICON_SVG_BODY = {
    "calendar": """
        <rect x="4" y="5" width="16" height="15" rx="2"/>
        <path d="M8 3v4M16 3v4M4 10h16"/>
        <rect x="10" y="13" width="4" height="4" rx="1"/>
    """,
    "plus": """
        <rect x="4" y="4" width="16" height="16" rx="2"/>
        <path d="M12 8v8M8 12h8"/>
    """,
    "server": """
        <rect x="4" y="4" width="16" height="6" rx="1.5"/>
        <rect x="4" y="14" width="16" height="6" rx="1.5"/>
        <path d="M8 7h.01M8 17h.01M12 7h5M12 17h5"/>
    """,
    "log": """
        <path d="M7 3h7l4 4v14H7z"/>
        <path d="M14 3v5h5M10 12h6M10 16h6M10 8h1"/>
    """,
    "settings": """
        <circle cx="12" cy="12" r="3"/>
        <path d="M12 2v3M12 19v3M4.93 4.93l2.12 2.12M16.95 16.95l2.12 2.12M2 12h3M19 12h3M4.93 19.07l2.12-2.12M16.95 7.05l2.12-2.12"/>
    """,
    "code": """
        <path d="M8 8l-4 4 4 4M16 8l4 4-4 4M14 4l-4 16"/>
    """,
    "bolt": """
        <path d="M13 2L5 14h6l-1 8 9-13h-6z" fill="{color}" stroke="none"/>
    """,
    "shield": """
        <path d="M12 3l7 3v5c0 5-3.5 8-7 10-3.5-2-7-5-7-10V6z"/>
        <path d="M9 12l2 2 4-5"/>
    """,
    "table": """
        <rect x="4" y="4" width="16" height="16" rx="2"/>
        <path d="M4 10h16M4 15h16M10 4v16"/>
    """,
    "database": """
        <ellipse cx="12" cy="5" rx="7" ry="3"/>
        <path d="M5 5v6c0 1.7 3.1 3 7 3s7-1.3 7-3V5"/>
        <path d="M5 11v6c0 1.7 3.1 3 7 3s7-1.3 7-3v-6"/>
    """,
    "file": """
        <path d="M7 3h7l4 4v14H7z"/>
        <path d="M14 3v5h5M10 12h5M10 16h5"/>
    """,
    "trash": """
        <path d="M4 7h16M9 7V4h6v3M7 7l1 14h8l1-14M10 11v6M14 11v6"/>
    """,
    "play": """
        <path d="M8 5v14l11-7z" fill="{color}" stroke="none"/>
    """,
    "stop": """
        <rect x="7" y="7" width="10" height="10" rx="2" fill="{color}" stroke="none"/>
    """,
    "rocket": """
        <path d="M14 4c3 1 5 3 6 6l-5 5c-1.6-.4-3.6-2.4-4-4z"/>
        <circle cx="15" cy="9" r="1.5"/>
        <path d="M10 14l-3 3M11 8L7 7 5 9l4 2M16 13l1 4-2 2-2-4"/>
    """,
    "network": """
        <circle cx="12" cy="5" r="2"/>
        <circle cx="5" cy="18" r="2"/>
        <circle cx="19" cy="18" r="2"/>
        <path d="M12 7v4M6.7 16.7l3.8-3.8M17.3 16.7l-3.8-3.8"/>
    """,
    "user": """
        <circle cx="12" cy="8" r="4"/>
        <path d="M5 21c1.5-4 12.5-4 14 0"/>
    """,
    "download": """
        <path d="M12 4v10M8 10l4 4 4-4M5 20h14"/>
    """,
    "external": """
        <path d="M14 4h6v6M20 4l-9 9"/>
        <path d="M18 13v6H5V6h6"/>
    """,
    "branch": """
        <circle cx="6" cy="5" r="2"/>
        <circle cx="18" cy="12" r="2"/>
        <circle cx="6" cy="19" r="2"/>
        <path d="M6 7v10M8 12h8"/>
    """,
    "refresh": """
        <path d="M20 6v5h-5M4 18v-5h5"/>
        <path d="M18 9a7 7 0 0 0-12-3M6 15a7 7 0 0 0 12 3"/>
    """,
    "folder": """
        <path d="M3 6h7l2 3h9v10H3z"/>
        <path d="M3 9h18"/>
    """,
    "help": """
        <circle cx="12" cy="12" r="9"/>
        <path d="M9.5 9a2.8 2.8 0 0 1 5 1.7c0 2-2.5 2.2-2.5 4.3M12 18h.01"/>
    """,
    "save": """
        <path d="M5 3h12l2 2v16H5z"/>
        <path d="M8 3v6h8V3M8 21v-7h8v7"/>
    """,
    "check": """
        <path d="M20 6L9 17l-5-5"/>
    """,
    "link": """
        <path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/>
        <path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/>
    """,
    "edit": """
        <path d="M4 20h4l11-11-4-4L4 16z"/>
        <path d="M13 7l4 4"/>
    """,
    "eye": """
        <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/>
        <circle cx="12" cy="12" r="3"/>
    """,
    "eye_off": """
        <path d="M3 3l18 18"/>
        <path d="M10.6 5.2A10.8 10.8 0 0 1 12 5c6 0 10 7 10 7a18.6 18.6 0 0 1-3 4.1"/>
        <path d="M6.5 6.5C3.7 8.4 2 12 2 12s4 7 10 7a9.8 9.8 0 0 0 4.1-.9"/>
        <path d="M9.9 9.9A3 3 0 0 0 14.1 14.1"/>
    """,
}


def make_line_icon(kind: str, color: str = "#c6d7ef", size: int = 18) -> QIcon:
    """Render a unified SVG line icon matching the reference-style toolbar icons."""
    pixmap = QPixmap(size, size)
    pixmap.fill(Qt.GlobalColor.transparent)
    body = _ICON_SVG_BODY.get(kind) or '<circle cx="12" cy="12" r="6"/>'
    body = body.replace("{color}", color)
    svg = f"""
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
         fill="none" stroke="{color}" stroke-width="2"
         stroke-linecap="round" stroke-linejoin="round">
        {body}
    </svg>
    """
    renderer = QSvgRenderer(QByteArray(svg.encode("utf-8")))
    painter = QPainter(pixmap)
    painter.setRenderHint(QPainter.RenderHint.Antialiasing)
    renderer.render(painter)
    painter.end()
    return QIcon(pixmap)


def set_button_icon(button: QPushButton, kind: str, color: str = "#c6d7ef", size: int = 18):
    button.setIcon(make_line_icon(kind, color, size))
    button.setIconSize(QSize(size, size))


class CopyableIpLabel(QLabel):
    """点击复制本机 IP。"""

    def __init__(self, ip: str, parent=None):
        super().__init__(parent)
        self.ip = ip
        self._default_text = f"本机IP： {ip}"
        self.setText(self._default_text)
        self.setToolTip("点击复制本机 IP")
        self.setCursor(Qt.CursorShape.PointingHandCursor)

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            QApplication.clipboard().setText(self.ip)
            self.setText("已复制")
            QTimer.singleShot(1200, lambda: self.setText(self._default_text))
            event.accept()
            return
        super().mousePressEvent(event)


def button_style(variant: str = "outline", compact: bool = False) -> str:
    """统一按钮样式：匹配浅色主界面的视觉层级。"""
    palette = {
        "primary": ("#4f8cff", "#e8eef7", "#4f8cff", "#3f7df0", "#356bd0"),
        "success": ("#25c889", "#0f1b16", "#25c889", "#1fad75", "#16895f"),
        "outline": ("#2b313c", "#c6d7ef", "#4f6b92", "#263a55", "#2b4d75"),
        "danger": ("#342229", "#ff5c6a", "#8b3941", "#3e2730", "#4a2b34"),
        "neutral": ("#242932", "#aab4c3", "#3a4352", "#2b313c", "#20242c"),
    }
    bg, fg, border, hover, pressed = palette.get(variant, palette["outline"])
    padding = "5px 10px" if compact else "8px 14px"
    radius = "5px" if compact else "6px"
    min_height = "24px" if compact else "30px"
    return f"""
        QPushButton {{
            background-color: {bg};
            color: {fg};
            border: 1px solid {border};
            border-radius: {radius};
            padding: {padding};
            min-height: {min_height};
            font-size: 13px;
            font-weight: 600;
        }}
        QPushButton:hover {{
            background-color: {hover};
        }}
        QPushButton:pressed {{
            background-color: {pressed};
        }}
        QPushButton:disabled {{
            background-color: #20242c;
            color: #778398;
            border-color: #3a4352;
        }}
    """


def apply_button_style(button: QPushButton, variant: str = "outline", compact: bool = False):
    button.setCursor(Qt.CursorShape.PointingHandCursor)
    button.setStyleSheet(button_style(variant, compact))
