"""
Modern Blue Theme Demo Application
==================================

Demonstrates the Modern Blue Qt stylesheet theme with various Qt components.
This serves as both a showcase and a testing application.

Usage:
    python demo.py
"""

import sys

try:
    from PySide2.QtCore import Qt, QTimer
    from PySide2.QtWidgets import (
        QAction,
        QApplication,
        QCalendarWidget,
        QCheckBox,
        QComboBox,
        QDateEdit,
        QDateTimeEdit,
        QDoubleSpinBox,
        QGroupBox,
        QHBoxLayout,
        QHeaderView,
        QLabel,
        QLineEdit,
        QListWidget,
        QMainWindow,
        QMessageBox,
        QProgressBar,
        QPushButton,
        QRadioButton,
        QSlider,
        QSpinBox,
        QStatusBar,
        QTableWidget,
        QTableWidgetItem,
        QTabWidget,
        QTextEdit,
        QVBoxLayout,
        QWidget,
    )
except ImportError as e:
    raise RuntimeError("Error: This script requires PySide2 to be installed.") from e


from styles.modern_blue import ModernBlueTheme


class DemoWindow(QMainWindow):
    """Main demo window showcasing the Modern Blue theme."""

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Modern Blue Theme Demo")
        self.setGeometry(100, 100, 1000, 700)

        # Apply the theme
        self.setStyleSheet(ModernBlueTheme.get_stylesheet())

        self._create_menu_bar()
        self._create_central_widget()
        self._create_status_bar()
        self._setup_demo_timer()

    def _create_menu_bar(self):
        """Create demonstration menu bar."""
        menubar = self.menuBar()

        # File menu
        file_menu = menubar.addMenu("文件(&F)")
        new_action = QAction("新建(&N)", self)
        open_action = QAction("打开(&O)", self)
        save_action = QAction("保存(&S)", self)
        exit_action = QAction("退出(&X)", self)
        exit_action.triggered.connect(self.close)

        file_menu.addAction(new_action)
        file_menu.addAction(open_action)
        file_menu.addAction(save_action)
        file_menu.addSeparator()
        file_menu.addAction(exit_action)

        # Edit menu
        edit_menu = menubar.addMenu("编辑(&E)")
        undo_action = QAction("撤销(&U)", self)
        redo_action = QAction("重做(&R)", self)
        edit_menu.addAction(undo_action)
        edit_menu.addAction(redo_action)

        # Help menu
        help_menu = menubar.addMenu("帮助(&H)")
        about_action = QAction("关于(&A)", self)
        about_action.triggered.connect(self._show_about)
        help_menu.addAction(about_action)

    def _create_central_widget(self):
        """Create the main content area with demo components."""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 20, 20, 20)

        # Title
        title_label = QLabel("Modern Blue Theme Demonstration")
        title_label.setObjectName("titleLabel")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("""
            font-size: 24px;
            font-weight: 600;
            color: #0f172a;
            margin: 20px;
        """)
        main_layout.addWidget(title_label)

        # Create tab widget for different component categories
        tab_widget = QTabWidget()
        main_layout.addWidget(tab_widget)

        # Basic Controls Tab
        tab_widget.addTab(self._create_basic_controls_tab(), "基础控件")

        # Input Controls Tab
        tab_widget.addTab(self._create_input_controls_tab(), "输入控件")

        # Selection Controls Tab
        tab_widget.addTab(self._create_selection_controls_tab(), "选择控件")

        # Display Controls Tab
        tab_widget.addTab(self._create_display_controls_tab(), "显示控件")

        # Special Components Tab
        tab_widget.addTab(self._create_special_components_tab(), "特殊组件")

    def _create_basic_controls_tab(self):
        """Create tab with basic control components."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Buttons group
        button_group = QGroupBox("按钮控件")
        button_layout = QHBoxLayout(button_group)

        btn_primary = QPushButton("主要按钮")
        btn_secondary = QPushButton("次要按钮")
        btn_disabled = QPushButton("禁用按钮")
        btn_disabled.setEnabled(False)
        btn_flat = QPushButton("扁平按钮")
        btn_flat.setProperty("class", "flat")

        button_layout.addWidget(btn_primary)
        button_layout.addWidget(btn_secondary)
        button_layout.addWidget(btn_disabled)
        button_layout.addWidget(btn_flat)
        button_layout.addStretch()

        # Labels group
        label_group = QGroupBox("标签控件")
        label_layout = QVBoxLayout(label_group)

        label_normal = QLabel("这是一个普通标签")
        label_bold = QLabel("这是一个粗体标签")
        label_bold.setStyleSheet("font-weight: 600; font-size: 16px;")
        label_colored = QLabel("这是一个彩色标签")
        label_colored.setStyleSheet("color: #3b82f6; font-size: 16px;")

        label_layout.addWidget(label_normal)
        label_layout.addWidget(label_bold)
        label_layout.addWidget(label_colored)

        layout.addWidget(button_group)
        layout.addWidget(label_group)
        layout.addStretch()

        return widget

    def _create_input_controls_tab(self):
        """Create tab with input control components."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Text inputs group
        text_group = QGroupBox("文本输入")
        text_layout = QVBoxLayout(text_group)

        line_edit = QLineEdit()
        line_edit.setPlaceholderText("单行文本输入框")

        text_area = QTextEdit()
        text_area.setPlaceholderText("多行文本输入框\n可以输入更多内容...")
        text_area.setMaximumHeight(100)

        text_layout.addWidget(QLabel("单行输入:"))
        text_layout.addWidget(line_edit)
        text_layout.addWidget(QLabel("多行输入:"))
        text_layout.addWidget(text_area)

        # Numeric inputs group
        numeric_group = QGroupBox("数值输入")
        numeric_layout = QHBoxLayout(numeric_group)

        spin_int = QSpinBox()
        spin_int.setRange(0, 100)
        spin_int.setValue(50)

        spin_double = QDoubleSpinBox()
        spin_double.setRange(0.0, 100.0)
        spin_double.setValue(25.5)
        spin_double.setDecimals(2)

        numeric_layout.addWidget(QLabel("整数:"))
        numeric_layout.addWidget(spin_int)
        numeric_layout.addWidget(QLabel("小数:"))
        numeric_layout.addWidget(spin_double)
        numeric_layout.addStretch()

        # Combo boxes group
        combo_group = QGroupBox("下拉选择")
        combo_layout = QHBoxLayout(combo_group)

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

        combo_editable = QComboBox()
        combo_editable.setEditable(True)
        combo_editable.addItems(["可编辑选项 1", "可编辑选项 2"])

        combo_layout.addWidget(QLabel("普通下拉:"))
        combo_layout.addWidget(combo_simple)
        combo_layout.addWidget(QLabel("可编辑下拉:"))
        combo_layout.addWidget(combo_editable)
        combo_layout.addStretch()

        # Date/time inputs group
        datetime_group = QGroupBox("日期时间")
        datetime_layout = QHBoxLayout(datetime_group)

        date_edit = QDateEdit()
        date_edit.setDisplayFormat("yyyy-MM-dd")

        datetime_edit = QDateTimeEdit()
        datetime_edit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")

        datetime_layout.addWidget(QLabel("日期:"))
        datetime_layout.addWidget(date_edit)
        datetime_layout.addWidget(QLabel("日期时间:"))
        datetime_layout.addWidget(datetime_edit)
        datetime_layout.addStretch()

        layout.addWidget(text_group)
        layout.addWidget(numeric_group)
        layout.addWidget(combo_group)
        layout.addWidget(datetime_group)
        layout.addStretch()

        return widget

    def _create_selection_controls_tab(self):
        """Create tab with selection control components."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Checkboxes group
        checkbox_group = QGroupBox("复选框")
        checkbox_layout = QVBoxLayout(checkbox_group)

        cb_enabled = QCheckBox("启用选项")
        cb_enabled.setChecked(True)
        cb_disabled = QCheckBox("禁用选项")
        cb_disabled.setChecked(False)
        cb_disabled.setEnabled(False)
        cb_tristate = QCheckBox("三态复选框")
        cb_tristate.setTristate(True)
        cb_tristate.setCheckState(Qt.PartiallyChecked)

        checkbox_layout.addWidget(cb_enabled)
        checkbox_layout.addWidget(cb_disabled)
        checkbox_layout.addWidget(cb_tristate)

        # Radio buttons group
        radio_group = QGroupBox("单选按钮")
        radio_layout = QVBoxLayout(radio_group)

        rb_option1 = QRadioButton("选项一")
        rb_option1.setChecked(True)
        rb_option2 = QRadioButton("选项二")
        rb_option3 = QRadioButton("选项三")

        radio_layout.addWidget(rb_option1)
        radio_layout.addWidget(rb_option2)
        radio_layout.addWidget(rb_option3)

        # Lists group
        list_group = QGroupBox("列表控件")
        list_layout = QHBoxLayout(list_group)

        # List widget
        list_widget = QListWidget()
        items = [f"列表项目 {i}" for i in range(1, 11)]
        list_widget.addItems(items)
        list_widget.setMaximumHeight(150)

        # Table widget
        table_widget = QTableWidget(5, 3)
        table_widget.setHorizontalHeaderLabels(["姓名", "年龄", "城市"])
        table_widget.setMaximumHeight(150)

        # Populate table
        data = [
            ["张三", "25", "北京"],
            ["李四", "30", "上海"],
            ["王五", "28", "广州"],
            ["赵六", "35", "深圳"],
            ["钱七", "22", "杭州"],
        ]

        for row, rowData in enumerate(data):
            for col, cellData in enumerate(rowData):
                table_widget.setItem(row, col, QTableWidgetItem(cellData))

        table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        list_layout.addWidget(QLabel("列表:"))
        list_layout.addWidget(list_widget)
        list_layout.addWidget(QLabel("表格:"))
        list_layout.addWidget(table_widget)

        layout.addWidget(checkbox_group)
        layout.addWidget(radio_group)
        layout.addWidget(list_group)
        layout.addStretch()

        return widget

    def _create_display_controls_tab(self):
        """Create tab with display control components."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Progress bars group
        progress_group = QGroupBox("进度条")
        progress_layout = QVBoxLayout(progress_group)

        pb_determinate = QProgressBar()
        pb_determinate.setValue(65)
        pb_determinate.setFormat("完成进度: %p%")

        pb_indeterminate = QProgressBar()
        pb_indeterminate.setRange(0, 0)  # Indeterminate

        progress_layout.addWidget(QLabel("确定进度:"))
        progress_layout.addWidget(pb_determinate)
        progress_layout.addWidget(QLabel("不确定进度:"))
        progress_layout.addWidget(pb_indeterminate)

        # Sliders group
        slider_group = QGroupBox("滑块")
        slider_layout = QVBoxLayout(slider_group)

        slider_horizontal = QSlider(Qt.Horizontal)
        slider_horizontal.setRange(0, 100)
        slider_horizontal.setValue(50)

        slider_layout.addWidget(QLabel("水平滑块:"))
        slider_layout.addWidget(slider_horizontal)

        # Status displays group
        status_group = QGroupBox("状态显示")
        status_layout = QVBoxLayout(status_group)

        status_ready = QLabel("准备就绪")
        status_ready.setObjectName("StatusLabelReady")
        status_ready.setStyleSheet("""
            padding: 10px;
            border-radius: 6px;
            font-weight: 500;
        """)

        status_success = QLabel("操作成功")
        status_success.setObjectName("StatusLabelSuccess")
        status_success.setStyleSheet("""
            padding: 10px;
            border-radius: 6px;
            font-weight: 500;
        """)

        status_error = QLabel("操作失败")
        status_error.setObjectName("StatusLabelError")
        status_error.setStyleSheet("""
            padding: 10px;
            border-radius: 6px;
            font-weight: 500;
        """)

        status_warning = QLabel("警告信息")
        status_warning.setObjectName("StatusLabelWarning")
        status_warning.setStyleSheet("""
            padding: 10px;
            border-radius: 6px;
            font-weight: 500;
        """)

        status_layout.addWidget(status_ready)
        status_layout.addWidget(status_success)
        status_layout.addWidget(status_error)
        status_layout.addWidget(status_warning)

        layout.addWidget(progress_group)
        layout.addWidget(slider_group)
        layout.addWidget(status_group)
        layout.addStretch()

        return widget

    def _create_special_components_tab(self):
        """Create tab with special components."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Calendar group
        calendar_group = QGroupBox("日历控件")
        calendar_layout = QVBoxLayout(calendar_group)

        calendar = QCalendarWidget()
        calendar.setMaximumHeight(200)

        calendar_layout.addWidget(calendar)

        # Tooltip demo
        tooltip_group = QGroupBox("工具提示演示")
        tooltip_layout = QVBoxLayout(tooltip_group)

        tooltip_button = QPushButton("悬停查看工具提示")
        tooltip_button.setToolTip("这是一个工具提示信息\n可以包含多行文本")

        tooltip_layout.addWidget(tooltip_button)

        # Custom styled widgets
        custom_group = QGroupBox("自定义样式组件")
        custom_layout = QVBoxLayout(custom_group)

        # Success result area
        success_result = QTextEdit()
        success_result.setObjectName("successResult")
        success_result.setPlainText("这是成功结果区域\n具有特殊的绿色样式")
        success_result.setMaximumHeight(80)

        # Warning input area
        warning_input = QLineEdit()
        warning_input.setObjectName("warningInput")
        warning_input.setPlaceholderText("这是警告输入区域")

        custom_layout.addWidget(QLabel("成功结果显示:"))
        custom_layout.addWidget(success_result)
        custom_layout.addWidget(QLabel("警告输入区域:"))
        custom_layout.addWidget(warning_input)

        layout.addWidget(calendar_group)
        layout.addWidget(tooltip_group)
        layout.addWidget(custom_group)
        layout.addStretch()

        return widget

    def _create_status_bar(self):
        """Create status bar with demo information."""
        status_bar = QStatusBar()
        self.setStatusBar(status_bar)

        status_bar.showMessage("Modern Blue Theme Demo - 就绪")

        # Add permanent widgets to status bar
        self.status_label = QLabel("状态: 正常")
        self.status_label.setObjectName("StatusLabelReady")
        status_bar.addPermanentWidget(self.status_label)

    def _setup_demo_timer(self):
        """Setup timer for demo animations."""
        self.demo_timer = QTimer()
        self.demo_timer.timeout.connect(self._update_demo)
        self.demo_timer.start(2000)  # Update every 2 seconds

        self.progress_value = 0

    def _update_demo(self):
        """Update demo elements periodically."""
        # Cycle through different status messages
        statuses = [
            ("StatusLabelReady", "状态: 正常"),
            ("StatusLabelSuccess", "状态: 成功"),
            ("StatusLabelWarning", "状态: 警告"),
            ("StatusLabelError", "状态: 错误"),
        ]

        import random

        status_style, status_text = random.choice(statuses)
        self.status_label.setObjectName(status_style)
        self.status_label.setText(status_text)

    def _show_about(self):
        """Show about dialog."""
        QMessageBox.about(
            self,
            "关于 Modern Blue Theme Demo",
            "Modern Blue Theme Demo v1.0\n\n"
            "这是一个展示 Modern Blue Qt 样式主题的演示程序。\n"
            "展示了各种 Qt 组件在该主题下的外观效果。",
        )


def main():
    """Main application entry point."""
    app = QApplication(sys.argv)

    # Apply theme to entire application
    app.setStyleSheet(ModernBlueTheme.get_stylesheet())

    # Create and show demo window
    window = DemoWindow()
    window.show()

    # Run application
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
