#!/usr/bin/env python3
"""
Live Theme Preview Demo
=======================

实时主题预览功能演示应用程序
"""

import sys
from pathlib import Path

# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

try:
    from PySide2.QtCore import Qt
    from PySide2.QtGui import QColor
    from PySide2.QtWidgets import (
        QApplication,
        QCheckBox,
        QColorDialog,
        QComboBox,
        QGroupBox,
        QHBoxLayout,
        QLabel,
        QListWidget,
        QMainWindow,
        QPushButton,
        QSlider,
        QSpinBox,
        QTabWidget,
        QTextEdit,
        QVBoxLayout,
        QWidget,
    )
except ImportError:
    print("请安装 PySide2: pip install PySide2")
    sys.exit(1)

from sfi.qtstyles import (
    DarkBlueTheme,
    HighContrastTheme,
    ModernBlueTheme,
    ThemeManager,
    get_theme_colors_enum,
)
from sfi.qtstyles.preview import (
    LiveThemeEditor,
    PreviewMode,
    bind_widget_to_preview,
    create_preview_manager,
)


class ThemePreviewDemo(QMainWindow):
    """主题预览演示窗口."""

    def __init__(self):
        super().__init__()
        self.init_ui()
        self.setup_preview_system()

    def init_ui(self):
        """初始化用户界面."""
        self.setWindowTitle("QtStyles 实时主题预览演示")
        self.setGeometry(100, 100, 1200, 800)

        # 创建中央控件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局
        main_layout = QHBoxLayout(central_widget)

        # 左侧控制面板
        control_panel = self.create_control_panel()
        main_layout.addWidget(control_panel, 1)

        # 右侧预览区域
        preview_area = self.create_preview_area()
        main_layout.addWidget(preview_area, 2)

    def create_control_panel(self) -> QWidget:
        """创建控制面板."""
        panel = QGroupBox("主题控制面板")
        layout = QVBoxLayout(panel)

        # 主题选择
        theme_group = QGroupBox("主题选择")
        theme_layout = QVBoxLayout(theme_group)

        self.theme_combo = QComboBox()
        self.theme_combo.addItems(["ModernBlue", "DarkBlue", "HighContrast"])
        self.theme_combo.currentTextChanged.connect(self.on_theme_changed)
        theme_layout.addWidget(QLabel("选择主题:"))
        theme_layout.addWidget(self.theme_combo)

        # 预览模式
        mode_group = QGroupBox("预览模式")
        mode_layout = QVBoxLayout(mode_group)

        self.mode_combo = QComboBox()
        self.mode_combo.addItems(["即时预览", "延迟预览", "批量预览"])
        self.mode_combo.setCurrentText("即时预览")
        self.mode_combo.currentTextChanged.connect(self.on_mode_changed)
        mode_layout.addWidget(QLabel("预览模式:"))
        mode_layout.addWidget(self.mode_combo)

        # 延迟设置
        self.delay_slider = QSlider(Qt.Horizontal)
        self.delay_slider.setRange(100, 1000)
        self.delay_slider.setValue(300)
        self.delay_slider.valueChanged.connect(self.on_delay_changed)

        self.delay_label = QLabel("延迟: 300ms")

        delay_layout = QHBoxLayout()
        delay_layout.addWidget(QLabel("延迟设置:"))
        delay_layout.addWidget(self.delay_slider)
        delay_layout.addWidget(self.delay_label)

        mode_layout.addLayout(delay_layout)

        # 动画设置
        animation_group = QGroupBox("动画效果")
        animation_layout = QVBoxLayout(animation_group)

        self.transition_checkbox = QCheckBox("启用过渡动画")
        self.transition_checkbox.setChecked(True)
        self.transition_checkbox.stateChanged.connect(self.on_animation_changed)

        self.duration_spinbox = QSpinBox()
        self.duration_spinbox.setRange(100, 2000)
        self.duration_spinbox.setValue(300)
        self.duration_spinbox.setSuffix(" ms")
        self.duration_spinbox.valueChanged.connect(self.on_duration_changed)

        animation_layout.addWidget(self.transition_checkbox)
        animation_layout.addWidget(QLabel("过渡时长:"))
        animation_layout.addWidget(self.duration_spinbox)

        # 颜色编辑
        color_group = QGroupBox("颜色编辑")
        color_layout = QVBoxLayout(color_group)

        self.color_list = QListWidget()
        self.color_list.itemClicked.connect(self.on_color_selected)
        color_layout.addWidget(QLabel("点击颜色进行编辑:"))
        color_layout.addWidget(self.color_list)

        self.edit_color_button = QPushButton("编辑选中颜色")
        self.edit_color_button.clicked.connect(self.edit_selected_color)
        color_layout.addWidget(self.edit_color_button)

        # 控制按钮
        button_layout = QHBoxLayout()

        self.apply_button = QPushButton("应用更改")
        self.apply_button.clicked.connect(self.apply_changes)

        self.reset_button = QPushButton("重置")
        self.reset_button.clicked.connect(self.reset_theme)

        self.undo_button = QPushButton("撤销")
        self.undo_button.clicked.connect(self.undo_change)

        button_layout.addWidget(self.apply_button)
        button_layout.addWidget(self.reset_button)
        button_layout.addWidget(self.undo_button)

        # 添加所有组件到主布局
        layout.addWidget(theme_group)
        layout.addWidget(mode_group)
        layout.addWidget(animation_group)
        layout.addWidget(color_group)
        layout.addLayout(button_layout)
        layout.addStretch()

        return panel

    def create_preview_area(self) -> QWidget:
        """创建预览区域."""
        tab_widget = QTabWidget()

        # 基础控件预览
        basic_widget = self.create_basic_controls_preview()
        tab_widget.addTab(basic_widget, "基础控件")

        # 复杂控件预览
        complex_widget = self.create_complex_controls_preview()
        tab_widget.addTab(complex_widget, "复杂控件")

        # 文本预览
        text_widget = self.create_text_preview()
        tab_widget.addTab(text_widget, "文本样式")

        return tab_widget

    def create_basic_controls_preview(self) -> QWidget:
        """创建基础控件预览."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # 按钮示例
        button_group = QGroupBox("按钮控件")
        button_layout = QVBoxLayout(button_group)

        self.test_button1 = QPushButton("主要按钮")
        self.test_button2 = QPushButton("次要按钮")
        self.test_button2.setProperty("class", "flat")

        button_layout.addWidget(self.test_button1)
        button_layout.addWidget(self.test_button2)

        # 输入控件示例
        input_group = QGroupBox("输入控件")
        input_layout = QVBoxLayout(input_group)

        self.test_lineedit = QTextEdit()
        self.test_lineedit.setPlaceholderText("请输入文本...")
        self.test_lineedit.setMaximumHeight(100)

        input_layout.addWidget(QLabel("文本输入:"))
        input_layout.addWidget(self.test_lineedit)

        # 组合框示例
        combo_group = QGroupBox("选择控件")
        combo_layout = QVBoxLayout(combo_group)

        self.test_combobox = QComboBox()
        self.test_combobox.addItems(["选项 1", "选项 2", "选项 3", "选项 4"])

        combo_layout.addWidget(QLabel("下拉选择:"))
        combo_layout.addWidget(self.test_combobox)

        # 标签示例
        label_group = QGroupBox("标签控件")
        label_layout = QVBoxLayout(label_group)

        self.test_label1 = QLabel("这是一个普通标签")
        self.test_label2 = QLabel("这是一个标题标签")
        self.test_label2.setProperty("class", "title")

        label_layout.addWidget(self.test_label1)
        label_layout.addWidget(self.test_label2)

        # 添加到主布局
        layout.addWidget(button_group)
        layout.addWidget(input_group)
        layout.addWidget(combo_group)
        layout.addWidget(label_group)
        layout.addStretch()

        return widget

    def create_complex_controls_preview(self) -> QWidget:
        """创建复杂控件预览."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # 列表控件
        list_group = QGroupBox("列表控件")
        list_layout = QVBoxLayout(list_group)

        self.test_listwidget = QListWidget()
        self.test_listwidget.addItems(
            [
                "列表项目 1",
                "列表项目 2",
                "列表项目 3",
                "列表项目 4",
                "列表项目 5",
            ]
        )

        list_layout.addWidget(QLabel("列表视图:"))
        list_layout.addWidget(self.test_listwidget)

        # 进度条
        progress_group = QGroupBox("进度控件")
        QVBoxLayout(progress_group)

        # 这里可以添加进度条控件

        layout.addWidget(list_group)
        layout.addWidget(progress_group)
        layout.addStretch()

        return widget

    def create_text_preview(self) -> QWidget:
        """创建文本预览."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        self.text_preview = QTextEdit()
        self.text_preview.setPlainText(
            """
这是一个文本预览区域，用于展示不同主题下的文本样式效果。

支持的功能包括：
• 不同的字体族和大小
• 多种颜色方案
• 各种文本权重
• 响应式布局调整

您可以在这里测试各种文本相关的主题设置。
        """.strip()
        )

        layout.addWidget(QLabel("文本预览:"))
        layout.addWidget(self.text_preview)

        return widget

    def setup_preview_system(self):
        """设置预览系统."""
        # 创建预览管理器
        self.preview_manager = create_preview_manager()
        self.live_editor = LiveThemeEditor(self.preview_manager)

        # 绑定所有预览控件
        preview_widgets = [
            self.test_button1,
            self.test_button2,
            self.test_lineedit,
            self.test_combobox,
            self.test_label1,
            self.test_label2,
            self.test_listwidget,
            self.text_preview,
        ]

        for widget in preview_widgets:
            bind_widget_to_preview(widget, self.preview_manager)

        # 初始化颜色列表
        self.update_color_list()

        # 应用初始主题
        self.apply_theme("ModernBlue")

    def update_color_list(self):
        """更新颜色列表."""
        self.color_list.clear()
        Color = get_theme_colors_enum()

        for color_name in Color.__members__:
            color_value = getattr(Color, color_name).value
            item_text = f"{color_name}: {color_value}"
            self.color_list.addItem(item_text)

    def on_theme_changed(self, theme_name: str):
        """主题更改回调."""
        theme_mapping = {
            "ModernBlue": "ModernBlue",
            "DarkBlue": "DarkBlue",
            "HighContrast": "HighContrast",
        }

        actual_theme = theme_mapping.get(theme_name, "ModernBlue")
        self.apply_theme(actual_theme)

    def apply_theme(self, theme_name: str):
        """应用主题."""
        success = ThemeManager.apply_theme(theme_name, self)
        if success:
            self.preview_manager.commit_preview(theme_name)
            self.update_color_list()

    def on_mode_changed(self, mode_text: str):
        """预览模式更改回调."""
        mode_mapping = {
            "即时预览": PreviewMode.INSTANT,
            "延迟预览": PreviewMode.DELAYED,
            "批量预览": PreviewMode.BATCH,
        }

        mode = mode_mapping.get(mode_text, PreviewMode.INSTANT)
        config = self.preview_manager.get_preview_config()
        config.mode = mode
        self.preview_manager.set_preview_config(config)

    def on_delay_changed(self, value: int):
        """延迟值更改回调."""
        self.delay_label.setText(f"延迟: {value}ms")
        config = self.preview_manager.get_preview_config()
        config.delay_ms = value
        self.preview_manager.set_preview_config(config)

    def on_animation_changed(self, state: int):
        """动画设置更改回调."""
        enabled = state == Qt.Checked
        config = self.preview_manager.get_preview_config()
        config.enable_transitions = enabled
        self.preview_manager.set_preview_config(config)

    def on_duration_changed(self, value: int):
        """过渡时长更改回调."""
        config = self.preview_manager.get_preview_config()
        config.transition_duration = value / 1000.0
        self.preview_manager.set_preview_config(config)

    def on_color_selected(self, item):
        """颜色选择回调."""
        # 实现颜色选择逻辑
        pass

    def edit_selected_color(self):
        """编辑选中颜色."""
        current_item = self.color_list.currentItem()
        if not current_item:
            return

        # 解析当前颜色
        item_text = current_item.text()
        color_name = item_text.split(":")[0].strip()

        # 获取当前颜色值
        Color = get_theme_colors_enum()
        current_color = getattr(Color, color_name).value

        # 打开颜色选择对话框
        color = QColor(current_color)
        dialog = QColorDialog(color, self)
        dialog.setWindowTitle(f"编辑颜色: {color_name}")

        if dialog.exec_() == QColorDialog.Accepted:
            new_color = dialog.selectedColor()
            if new_color.isValid():
                hex_color = new_color.name()
                self.live_editor.edit_color(color_name, hex_color)
                self.update_color_list()

    def apply_changes(self):
        """应用更改."""
        current_theme = self.preview_manager.state.current_theme
        if current_theme:
            self.apply_theme(current_theme)

    def reset_theme(self):
        """重置主题."""
        current_theme = self.preview_manager.state.current_theme or "ModernBlue"
        self.apply_theme(current_theme)
        self.live_editor = LiveThemeEditor(self.preview_manager)

    def undo_change(self):
        """撤销更改."""
        if self.live_editor.undo():
            # 更新预览
            current_theme = self.preview_manager.state.current_theme
            if current_theme:
                self.apply_theme(current_theme)


def main():
    """主函数."""
    app = QApplication(sys.argv)

    # 注册主题
    ThemeManager.register_theme("ModernBlue", ModernBlueTheme)
    ThemeManager.register_theme("DarkBlue", DarkBlueTheme)
    ThemeManager.register_theme("HighContrast", HighContrastTheme)

    # 创建并显示主窗口
    window = ThemePreviewDemo()
    window.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
