# -*- coding: utf-8 -*-
"""系列 / 章节对话框：快速新建 + 完整管理。"""
from __future__ import annotations

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QComboBox,
    QDialog,
    QDialogButtonBox,
    QFormLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QListWidget,
    QMessageBox,
    QPushButton,
    QSpinBox,
    QVBoxLayout,
)

from ..db import Database
from ..models import SERIES_STATUS, Chapter, Series
from .theme import ACCENT, BG_CARD, BG_HOVER, BORDER_LIGHT, FG, FG_DIM

_BTN_QSS = f"""
QPushButton {{
    background: {ACCENT}; color: white; border: none; border-radius: 6px;
    padding: 8px 20px; font-weight: 600;
}}
QPushButton:hover {{ background: #5BA0E9; }}
QPushButton#Ghost {{ background: {BG_CARD}; color: {FG}; border: 1px solid {BORDER_LIGHT}; }}
QPushButton#Ghost:hover {{ background: {BG_HOVER}; }}
"""


class _BaseDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet(_BTN_QSS)


# ---------------------------------------------------------------------------
# 快速新建系列
# ---------------------------------------------------------------------------
class QuickSeriesDialog(_BaseDialog):
    """最小化新建系列对话框。返回 (name, author)。"""

    def __init__(self, title: str, parent=None):
        super().__init__(parent)
        self.setWindowTitle(title)
        self.setMinimumWidth(380)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(18, 16, 18, 12)
        lay.setSpacing(10)

        self.name = QLineEdit()
        self.name.setPlaceholderText("系列名称，例如「星际旅人」")
        self.name.setFocus()
        lay.addWidget(QLabel("名称"))
        lay.addWidget(self.name)

        lay.addWidget(QLabel("作者 / 工作室"))
        self.author = QLineEdit()
        self.author.setPlaceholderText("可选")
        lay.addWidget(self.author)

        lay.addWidget(QLabel("状态"))
        self.status = QComboBox()
        for k, v in SERIES_STATUS.items():
            self.status.addItem(v, k)
        lay.addWidget(self.status)

        bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok |
                              QDialogButtonBox.StandardButton.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        lay.addWidget(bb)

    @staticmethod
    def ask(title: str, parent=None):
        d = QuickSeriesDialog(title, parent)
        if d.exec() == QDialog.DialogCode.Accepted:
            return d.name.text().strip(), d.author.text().strip()
        return None, None

    def get(self):
        return self.name.text().strip(), self.author.text().strip(), self.status.currentData()


# ---------------------------------------------------------------------------
# 快速新建章节
# ---------------------------------------------------------------------------
class QuickChapterDialog(_BaseDialog):
    """快速新建章节：卷号 + 话号 + 标题。返回 (volume, number, title)。"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("新建章节")
        self.setMinimumWidth(360)
        lay = QVBoxLayout(self)
        lay.setContentsMargins(18, 16, 18, 12)
        lay.setSpacing(8)

        lay.addWidget(QLabel("卷号（留空表示不分卷）"))
        self.vol = QSpinBox()
        self.vol.setRange(0, 9999)
        self.vol.setSpecialValueText("—")
        lay.addWidget(self.vol)

        lay.addWidget(QLabel("话号"))
        self.num = QSpinBox()
        self.num.setRange(1, 99999)
        self.num.setValue(1)
        lay.addWidget(self.num)

        lay.addWidget(QLabel("标题"))
        self.title = QLineEdit()
        self.title.setPlaceholderText("例如「觉醒」")
        self.title.setFocus()
        lay.addWidget(self.title)

        bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok |
                              QDialogButtonBox.StandardButton.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        lay.addWidget(bb)

    @staticmethod
    def ask(parent=None):
        d = QuickChapterDialog(parent)
        if d.exec() == QDialog.DialogCode.Accepted:
            vol = d.vol.value() or None
            return vol, d.num.value(), d.title.text().strip()
        return None, None, None


# ---------------------------------------------------------------------------
# 完整系列 / 章节管理
# ---------------------------------------------------------------------------
class SeriesManagerDialog(_BaseDialog):
    """左列表选系列，右侧编辑系列信息与章节表。"""

    def __init__(self, db: Database, parent=None):
        super().__init__(parent)
        self.db = db
        self.setWindowTitle("系列与章节管理")
        self.resize(760, 520)

        root = QHBoxLayout(self)
        root.setContentsMargins(16, 14, 16, 14)
        root.setSpacing(14)

        # ── 左：系列列表 ──
        left = QVBoxLayout()
        left.setSpacing(6)
        self.list = QListWidget()
        self.list.itemClicked.connect(self._select)
        left.addWidget(self.list, 1)

        btns = QHBoxLayout()
        btns.setSpacing(6)
        self.btn_add = QPushButton("＋ 新建")
        self.btn_add.clicked.connect(self._add)
        self.btn_del = QPushButton("🗑 删除")
        self.btn_del.setObjectName("Ghost")
        self.btn_del.clicked.connect(self._del)
        btns.addWidget(self.btn_add)
        btns.addWidget(self.btn_del)
        left.addLayout(btns)
        root.addLayout(left, 1)

        # ── 右：系列编辑 ──
        right = QVBoxLayout()
        right.setSpacing(8)
        t = QLabel("系列信息")
        t.setStyleSheet(f"color: {FG_DIM}; font-size: 12px; font-weight: 600;")
        right.addWidget(t)

        form = QFormLayout()
        form.setSpacing(8)
        self.e_name = QLineEdit()
        self.e_author = QLineEdit()
        self.e_status = QComboBox()
        for k, v in SERIES_STATUS.items():
            self.e_status.addItem(v, k)
        form.addRow("名称", self.e_name)
        form.addRow("作者", self.e_author)
        form.addRow("状态", self.e_status)
        right.addLayout(form)

        self.btn_save = QPushButton("💾 保存修改")
        self.btn_save.clicked.connect(self._save_series)
        right.addWidget(self.btn_save)

        right.addWidget(QLabel(""))
        t2 = QLabel("章节")
        t2.setStyleSheet(f"color: {FG_DIM}; font-size: 12px; font-weight: 600;")
        right.addWidget(t2)
        self.chap_list = QListWidget()
        right.addWidget(self.chap_list, 1)

        cbtns = QHBoxLayout()
        cbtns.setSpacing(6)
        b1 = QPushButton("＋ 新建章节")
        b1.clicked.connect(self._add_chapter)
        b2 = QPushButton("🗑 删除章节")
        b2.setObjectName("Ghost")
        b2.clicked.connect(self._del_chapter)
        cbtns.addWidget(b1)
        cbtns.addWidget(b2)
        cbtns.addStretch(1)
        right.addLayout(cbtns)
        root.addLayout(right, 1)

        self._cur_series_id = None
        self._cur_chapter_id = None
        self.refresh()

    def refresh(self):
        self.list.clear()
        for s in self.db.list_series():
            cnt = self.db.count_assets(series_id=s.id)
            self.list.addItem(f"{s.name}   ·   {cnt} 项   ·   {s.status_label}")
            self.list.item(self.list.count() - 1).setData(Qt.ItemDataRole.UserRole, s.id)

    def _select(self, item):
        sid = item.data(Qt.ItemDataRole.UserRole)
        s = self.db.get_series(sid)
        if not s:
            return
        self._cur_series_id = sid
        self.e_name.setText(s.name)
        self.e_author.setText(s.author)
        si = self.e_status.findIndex(s.status)
        self.e_status.setCurrentIndex(si if si >= 0 else 0)
        self._load_chapters()

    def _load_chapters(self):
        self.chap_list.clear()
        for c in self.db.list_chapters(self._cur_series_id):
            cnt = self.db.count_assets(chapter_id=c.id)
            self.chap_list.addItem(f"{c.label}   {c.title}   ·   {cnt} 项")
            self.chap_list.item(self.chap_list.count() - 1).setData(
                Qt.ItemDataRole.UserRole, c.id)

    def _add(self):
        name, author, status = QuickSeriesDialog.ask("新建系列", self)
        if not name:
            return
        s = self.db.create_series(Series(name=name, author=author, status=status or "ongoing"))
        self.refresh()
        self._select(self.list.item(0))

    def _del(self):
        item = self.list.currentItem()
        if not item:
            return
        sid = item.data(Qt.ItemDataRole.UserRole)
        s = self.db.get_series(sid)
        cnt = self.db.count_assets(series_id=sid)
        if QMessageBox.question(
            self, "确认删除",
            f"删除系列「{s.name}」？\n\n其中 {cnt} 项资产不会被删除，"
            f"但会从该系列中移除（保留在「未归类」）。",
        ) == QMessageBox.StandardButton.Yes:
            self.db.delete_series(sid)
            self.refresh()

    def _save_series(self):
        if not self._cur_series_id:
            return
        s = self.db.get_series(self._cur_series_id)
        if not s:
            return
        s.name = self.e_name.text().strip() or s.name
        s.author = self.e_author.text().strip()
        s.status = self.e_status.currentData() or s.status
        self.db.update_series(s)
        self.refresh()
        self._select(self.list.item(self.list.count() - 1))

    def _add_chapter(self):
        if not self._cur_series_id:
            QMessageBox.warning(self, "提示", "请先选择系列。")
            return
        vol, num, title = QuickChapterDialog.ask(self)
        if num is None:
            return
        self.db.create_chapter(Chapter(series_id=self._cur_series_id,
                                        volume=vol, number=num, title=title))
        self._load_chapters()

    def _del_chapter(self):
        item = self.chap_list.currentItem()
        if not item:
            return
        cid = item.data(Qt.ItemDataRole.UserRole)
        cnt = self.db.count_assets(chapter_id=cid)
        if QMessageBox.question(
            self, "确认删除",
            f"删除该章节？其中 {cnt} 项资产会保留但解除章节关联。",
        ) == QMessageBox.StandardButton.Yes:
            self.db.delete_chapter(cid)
            self._load_chapters()
