# -*- coding: utf-8 -*-
"""资产新建 / 编辑对话框。"""
from __future__ import annotations

import os
from pathlib import Path

from PySide6.QtWidgets import (
    QCheckBox,
    QComboBox,
    QDialog,
    QDialogButtonBox,
    QFileDialog,
    QGridLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QMessageBox,
    QPlainTextEdit,
    QPushButton,
    QSpinBox,
    QVBoxLayout,
    QWidget,
)

from ..db import Database
from ..library import copy_into_library
from ..models import (
    ASSET_TYPES_ORDERED, ASSET_TYPE_META, TEXT_TYPES,
    Asset, AssetType, Chapter, Series,
)
from .theme import FG_DIM


class AssetDialog(QDialog):
    """新建或编辑资产。

    用法::

        dlg = AssetDialog(db, parent=self)
        if dlg.exec() == QDialog.DialogCode.Accepted:
            asset = dlg.result_asset()
    """

    def __init__(self, db: Database, parent=None, asset: Asset | None = None,
                 default_series_id: int | None = None):
        super().__init__(parent)
        self.db = db
        self.editing = asset
        self.setWindowTitle("编辑资产" if asset else "新建资产")
        self.setMinimumWidth(560)
        self._asset = asset or Asset()

        body = QWidget()
        lay = QVBoxLayout(body)
        lay.setContentsMargins(20, 16, 20, 12)
        lay.setSpacing(12)

        # ── 标题 ──
        row1 = QHBoxLayout()
        self.title_edit = QLineEdit()
        self.title_edit.setPlaceholderText("资产标题，例如「第3话 · 开场」「艾伦·王 三视图」")
        self.title_edit.setText(self._asset.title)
        row1.addWidget(self.title_edit, 1)
        lay.addLayout(row1)

        # ── 类型 / 系列 ──
        grid = QGridLayout()
        grid.setHorizontalSpacing(14)
        grid.setVerticalSpacing(10)

        grid.addWidget(QLabel("类型", body), 0, 0)
        self.type_combo = QComboBox()
        for t in ASSET_TYPES_ORDERED:
            m = ASSET_TYPE_META[t]
            self.type_combo.addItem(f"{m.icon}  {m.label}", t.value)
        idx = self.type_combo.findData(self._asset.type.value)
        self.type_combo.setCurrentIndex(idx if idx >= 0 else 0)
        self.type_combo.currentIndexChanged.connect(self._on_type_changed)
        grid.addWidget(self.type_combo, 0, 1)

        grid.addWidget(QLabel("系列", body), 1, 0)
        series_row = QWidget()
        srl = QHBoxLayout(series_row)
        srl.setContentsMargins(0, 0, 0, 0)
        srl.setSpacing(6)
        self.series_combo = QComboBox()
        self.series_combo.addItem("— 未归类 —", None)
        for s in db.list_series():
            self.series_combo.addItem(s.name, s.id)
        if asset and asset.series_id:
            si = self.series_combo.findData(asset.series_id)
            if si >= 0:
                self.series_combo.setCurrentIndex(si)
        elif default_series_id:
            si = self.series_combo.findData(default_series_id)
            if si >= 0:
                self.series_combo.setCurrentIndex(si)
        self.btn_new_series = QPushButton("+")
        self.btn_new_series.setFixedWidth(28)
        self.btn_new_series.clicked.connect(self._quick_series)
        srl.addWidget(self.series_combo, 1)
        srl.addWidget(self.btn_new_series)
        grid.addWidget(series_row, 1, 1)

        grid.addWidget(QLabel("章节", body), 2, 0)
        chapter_row = QWidget()
        crl = QHBoxLayout(chapter_row)
        crl.setContentsMargins(0, 0, 0, 0)
        crl.setSpacing(6)
        self.chapter_combo = QComboBox()
        self.chapter_combo.addItem("— 无章节 —", None)
        sid = self.series_combo.currentData()
        for c in db.list_chapters(sid):
            crl_item = c.label
            self.chapter_combo.addItem(f"  {crl_item}  {c.title}".strip(), c.id)
        if asset and asset.chapter_id:
            ci = self.chapter_combo.findData(asset.chapter_id)
            if ci >= 0:
                self.chapter_combo.setCurrentIndex(ci)
        self.btn_new_chapter = QPushButton("+")
        self.btn_new_chapter.setFixedWidth(28)
        self.btn_new_chapter.clicked.connect(self._quick_chapter)
        crl.addWidget(self.chapter_combo, 1)
        crl.addWidget(self.btn_new_chapter)
        grid.addWidget(chapter_row, 2, 1)

        grid.addWidget(QLabel("页序", body), 3, 0)
        self.page_spin = QSpinBox()
        self.page_spin.setRange(0, 100000)
        self.page_spin.setSpecialValueText("—")
        self.page_spin.setValue(self._asset.page_index or 0)
        if self._asset.page_index is None:
            self.page_spin.setValue(0)
        grid.addWidget(self.page_spin, 3, 1)

        lay.addLayout(grid)
        self.series_combo.currentIndexChanged.connect(lambda _: self._refresh_chapters())

        # ── 文件 / 内容 ──
        self.file_box = QWidget()
        fl = QVBoxLayout(self.file_box)
        fl.setContentsMargins(0, 0, 0, 0)
        fl.setSpacing(6)
        self.file_row = QHBoxLayout()
        self.file_edit = QLineEdit()
        self.file_edit.setPlaceholderText("文件路径（留空可稍后补充）")
        self.file_edit.setReadOnly(True)
        self.file_edit.setText(self._asset.file_path)
        self.btn_browse = QPushButton("📂 选择文件")
        self.btn_browse.setObjectName("Ghost")
        self.btn_browse.clicked.connect(self._browse_file)
        self.file_row.addWidget(self.file_edit, 1)
        self.file_row.addWidget(self.btn_browse)
        fl.addLayout(self.file_row)
        self.copy_chk = QCheckBox("复制到资产库（推荐，原文件可随意移动）")
        self.copy_chk.setChecked(True)
        fl.addWidget(self.copy_chk)
        lay.addWidget(self.file_box)

        self.content_box = QWidget()
        cl = QVBoxLayout(self.content_box)
        cl.setContentsMargins(0, 0, 0, 0)
        self.content_hint = QLabel("剧本 / 分镜 / 备注正文：")
        self.content_hint.setStyleSheet(f"color: {FG_DIM}; font-size: 12px;")
        self.content_edit = QPlainTextEdit()
        self.content_edit.setPlaceholderText("输入文本内容…")
        self.content_edit.setPlainText(self._asset.content or "")
        self.content_edit.setFixedHeight(120)
        cl.addWidget(self.content_hint)
        cl.addWidget(self.content_edit)
        lay.addWidget(self.content_box)

        # ── 描述 / 标签 ──
        grid2 = QGridLayout()
        grid2.setHorizontalSpacing(14)
        grid2.setVerticalSpacing(10)

        grid2.addWidget(QLabel("描述", body), 0, 0)
        self.desc_edit = QLineEdit()
        self.desc_edit.setPlaceholderText("简短说明（可选）")
        self.desc_edit.setText(self._asset.description)
        grid2.addWidget(self.desc_edit, 0, 1)

        grid2.addWidget(QLabel("标签", body), 1, 0)
        self.tag_edit = QLineEdit()
        self.tag_edit.setPlaceholderText("用逗号分隔，例如：战斗, 主角, 高潮")
        self.tag_edit.setText(", ".join(self._asset.tags))
        grid2.addWidget(self.tag_edit, 1, 1)

        lay.addLayout(grid2)

        # ── 按钮 ──
        bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Save |
                              QDialogButtonBox.StandardButton.Cancel)
        bb.accepted.connect(self._accept)
        bb.rejected.connect(self.reject)
        lay.addWidget(bb)

        self.setLayout(lay)
        self._on_type_changed()

    # ------------------------------------------------------------------
    def _on_type_changed(self):
        t = AssetType.from_string(self.type_combo.currentData())
        is_text = t in TEXT_TYPES
        self.content_box.setVisible(is_text)
        self.file_box.setVisible(not is_text or t == AssetType.SCRIPT)
        self.copy_chk.setVisible(not is_text)
        # 文件过滤器随类型变化
        if t not in TEXT_TYPES:
            self._last_exts = ASSET_TYPE_META[t].exts

    def _refresh_chapters(self):
        self.chapter_combo.blockSignals(True)
        cur = self.chapter_combo.currentData()
        self.chapter_combo.clear()
        self.chapter_combo.addItem("— 无章节 —", None)
        sid = self.series_combo.currentData()
        for c in self.db.list_chapters(sid):
            self.chapter_combo.addItem(f"{c.label}  {c.title}".strip(), c.id)
        ci = self.chapter_combo.findData(cur)
        self.chapter_combo.setCurrentIndex(ci if ci >= 0 else 0)
        self.chapter_combo.blockSignals(False)

    def _quick_series(self):
        from .series_dialog import QuickSeriesDialog
        name, author = QuickSeriesDialog.ask("新建系列", self)
        if name:
            s = self.db.create_series(Series(name=name, author=author))
            self.series_combo.addItem(s.name, s.id)
            self.series_combo.setCurrentIndex(self.series_combo.count() - 1)

    def _quick_chapter(self):
        sid = self.series_combo.currentData()
        if not sid:
            QMessageBox.warning(self, "提示", "请先选择系列。")
            return
        from .series_dialog import QuickChapterDialog
        vol, num, title = QuickChapterDialog.ask(self)
        if num is not None:
            c = self.db.create_chapter(Chapter(series_id=sid, volume=vol, number=num, title=title))
            self._refresh_chapters()
            ci = self.chapter_combo.findData(c.id)
            self.chapter_combo.setCurrentIndex(ci if ci >= 0 else 0)

    def _browse_file(self):
        t = AssetType.from_string(self.type_combo.currentData())
        exts = ASSET_TYPE_META[t].exts
        filt = "支持格式 (" + " ".join(e.upper() for e in exts) + ");;所有文件 (*)"
        path = QFileDialog.getOpenFileName(self, "选择资产文件", os.path.expanduser("~"), filt)[0]
        if path:
            self.file_edit.setText(path)
            if not self.title_edit.text():
                self.title_edit.setText(Path(path).stem)

    def _accept(self):
        if not self.title_edit.text().strip():
            QMessageBox.warning(self, "提示", "标题不能为空。")
            return

        a = self.editing or Asset()
        a.title = self.title_edit.text().strip()
        a.type = AssetType.from_string(self.type_combo.currentData())
        a.series_id = self.series_combo.currentData()
        a.chapter_id = self.chapter_combo.currentData()
        v = self.page_spin.value()
        a.page_index = v if v else None
        a.file_path = self.file_edit.text().strip()
        a.content = self.content_edit.toPlainText()
        a.description = self.desc_edit.text().strip()
        a.tags = [s.strip() for s in self.tag_edit.text().split(",") if s.strip()]

        # 复制文件到资产库
        if a.file_path and self.copy_chk.isChecked():
            lib_root = Path(self.db.db_path).parent
            if a.series_id:
                s = self.db.get_series(a.series_id)
                if s is None:
                    s = Series(name="未归类")
            else:
                s = Series(name="未归类")
            a.file_path = str(copy_into_library(Path(a.file_path), s, a.type, lib_root))

        self._asset = a
        self.accept()

    def result_asset(self) -> Asset:
        return self._asset
