"""游戏库窗口：管理自己的游戏（AI 发明的 + 导入的），一键发布到房间。"""
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QListWidget, QListWidgetItem, QPushButton,
    QLabel, QFileDialog, QMessageBox,
)
from PyQt6.QtCore import Qt

from ui.window_base import OpenHamWindowBase
from ui import icons
from ui import theme
from core import game_library
from core.game_package import GamePackageError


class GameLibraryWindow(OpenHamWindowBase):
    def __init__(self, on_publish, on_invent, on_modify):
        super().__init__(title="加载游戏", shadow_size=0, min_w=520, min_h=460)
        self.title_lbl.setText("加载游戏")
        self._on_publish = on_publish    # on_publish(folder)
        self._on_invent = on_invent      # on_invent()
        self._on_modify = on_modify      # on_modify(folder)
        self._games = []
        self._build()

    def _build(self):
        root = QWidget()
        root.setObjectName("glRoot")
        root.setStyleSheet(self._qss())
        v = QVBoxLayout(root)
        v.setContentsMargins(16, 14, 16, 14)
        v.setSpacing(10)

        top = QHBoxLayout(); top.setSpacing(8)
        invent = QPushButton(" 发明新游戏")
        invent.setObjectName("ai")
        invent.setIcon(icons.qicon("ai"))
        invent.clicked.connect(self._invent)
        imp = QPushButton(" 导入游戏")
        imp.setIcon(icons.qicon("import"))
        imp.clicked.connect(self._import)
        top.addWidget(invent)
        top.addWidget(imp)
        top.addStretch()
        v.addLayout(top)

        self.hint = QLabel("")
        self.hint.setObjectName("hint")
        self.hint.setWordWrap(True)
        v.addWidget(self.hint)

        self.list = QListWidget()
        self.list.setObjectName("list")
        self.list.itemDoubleClicked.connect(lambda _i: self._publish())
        v.addWidget(self.list, 1)

        bot = QHBoxLayout(); bot.setSpacing(8)
        pub = QPushButton(" 发布到房间")
        pub.setObjectName("primary")
        pub.setIcon(icons.qicon("publish", color="#ffffff"))
        pub.clicked.connect(self._publish)
        modify = QPushButton(" AI 修改")
        modify.setObjectName("ai")
        modify.setIcon(icons.qicon("ai"))
        modify.clicked.connect(self._modify)
        dele = QPushButton(" 删除")
        dele.setIcon(icons.qicon("delete", color=theme.DANGER))
        dele.clicked.connect(self._delete)
        bot.addWidget(pub, 1)
        bot.addWidget(modify)
        bot.addWidget(dele)
        v.addLayout(bot)

        self.content_layout.addWidget(root)

    def _refresh(self):
        self.list.clear()
        self._games = game_library.list_games()
        for g in self._games:
            self.list.addItem(QListWidgetItem(icons.qicon("game"), g["name"]))
        if self._games:
            self.list.setCurrentRow(0)
            self.hint.setText("选一个游戏 → 发布到房间（双击也行）。")
        else:
            self.hint.setText("还没有游戏。点「发明新游戏」让 AI 现做一个，或「导入游戏」。")

    def _selected(self):
        i = self.list.currentRow()
        return self._games[i] if 0 <= i < len(self._games) else None

    def _publish(self):
        g = self._selected()
        if not g:
            self.hint.setText("请先在列表里选一个游戏。")
            return
        self.hide_window()
        self._on_publish(g["folder"])

    def _delete(self):
        g = self._selected()
        if not g:
            return
        if QMessageBox.question(self, "从游戏库移除", f"把「{g['name']}」从游戏库移除？\n（只是从库里移除，不影响已发布到房间的游戏）") == QMessageBox.StandardButton.Yes:
            game_library.delete_game(g["folder"])
            self._refresh()

    def _import(self):
        folder = QFileDialog.getExistingDirectory(self, "选择游戏文件夹（里面要有 index.html）")
        if not folder:
            return
        try:
            game_library.import_folder(folder)
            self._refresh()
            self.hint.setText(icons.richify("✅ 导入成功。"))
        except GamePackageError as e:
            self.hint.setText(icons.richify(f"⚠️ 导入失败：{e}"))

    def _invent(self):
        self.hide_window()
        self._on_invent()

    def _modify(self):
        g = self._selected()
        if not g:
            self.hint.setText("请先在列表里选一个要修改的游戏。")
            return
        self.hide_window()
        self._on_modify(g["folder"])

    def show_window(self):
        self._refresh()
        self.show_window_centered()
        self.raise_()
        self.activateWindow()

    def _qss(self) -> str:
        return f"""
            QWidget#glRoot {{ background: transparent; }}
            QLabel#hint {{ color: {theme.TEXT2}; font-size: 12px; }}
            QListWidget#list {{
                background: {theme.SURFACE}; color: {theme.TEXT};
                border: 1px solid {theme.BORDER}; border-radius: 10px; padding: 4px;
                font-size: 14px;
            }}
            QListWidget#list::item {{ padding: 9px 8px; border-radius: {theme.R_ITEM}px; }}
            QListWidget#list::item:selected {{ background: {theme.SELECT}; color: {theme.TEXT}; }}
            QPushButton {{
                background: {theme.SURFACE}; color: {theme.TEXT};
                border: 1px solid {theme.BORDER_IN}; border-radius: {theme.R_BTN}px; padding: 8px 14px; font-size: 13px;
            }}
            QPushButton:hover {{ background: {theme.SUBTLE}; }}
            QPushButton#primary {{ background: {theme.ACCENT}; color: #fff; font-weight: 600; border: none; }}
            QPushButton#primary:hover {{ background: {theme.ACCENT_HOV}; }}
            QPushButton#ai {{
                background: {theme.CARD}; color: {theme.INDIGO};
                border: 1px solid {theme.BORDER_IN}; font-weight: 500;
            }}
            QPushButton#ai:hover {{ background: {theme.INDIGO_SOFT}; border-color: #ddd8f3; }}
        """
