"""Settings Dialog module for widgets."""

from __future__ import annotations

from typing import Any

from PySide2.QtWidgets import (
    QCheckBox,
    QComboBox,
    QDialog,
    QDialogButtonBox,
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QSpinBox,
    QVBoxLayout,
)


class SettingsDialog(QDialog):
    """Settings dialog for scan options."""

    def __init__(self, parent: Any) -> None:  # noqa: ANN401
        """Initialize settings dialog.

        Args:
            parent: Parent widget (should be DocScanGUI instance)
            config_manager: ConfigManager instance
        """
        super().__init__(parent)
        self.main_window = parent
        self.setWindowTitle("扫描选项")
        self.setModal(True)
        self.resize(500, 400)
        self._create_ui()

    def _create_ui(self) -> None:
        """Create settings dialog UI."""
        layout = QVBoxLayout()

        # Language Settings Group
        self.language_group = QGroupBox("语言设置")
        language_layout = QHBoxLayout()
        language_layout.setSpacing(10)

        self.lang_label = QLabel("语言:")
        self.lang_combo = QComboBox()
        self.lang_combo.addItem("中文", "zh_CN")
        # 语言选择已禁用，只保留中文
        self.lang_combo.setEnabled(False)
        self.lang_combo.setToolTip("只支持中文")
        language_layout.addWidget(self.lang_label)
        language_layout.addWidget(self.lang_combo)
        language_layout.addStretch()
        self.language_group.setLayout(language_layout)
        layout.addWidget(self.language_group)

        # Processing Options Group
        processing_group = QGroupBox("处理选项")
        processing_layout = QVBoxLayout()
        processing_layout.setSpacing(10)

        self.ocr_checkbox = QCheckBox("使用 PDF OCR")
        self.ocr_checkbox.setToolTip("使用 PDF OCR")

        self.process_pool_checkbox = QCheckBox("使用进程池 (CPU 密集型)")
        self.process_pool_checkbox.setToolTip("使用进程池 (CPU 密集型)")

        self.include_images_checkbox = QCheckBox("包含图像格式")
        self.include_images_checkbox.setToolTip("包含图像格式")

        processing_layout.addWidget(self.ocr_checkbox)
        processing_layout.addWidget(self.process_pool_checkbox)
        processing_layout.addWidget(self.include_images_checkbox)
        processing_group.setLayout(processing_layout)
        layout.addWidget(processing_group)

        # Performance Settings Group
        performance_group = QGroupBox("性能设置")
        performance_layout = QFormLayout()
        performance_layout.setSpacing(12)

        # Thread count
        self.thread_spin = QSpinBox()
        self.thread_spin.setMinimum(1)
        self.thread_spin.setMaximum(16)
        self.thread_spin.setValue(4)
        self.thread_spin.setToolTip("线程数")
        performance_layout.addRow("线程数:", self.thread_spin)

        # Batch size
        self.batch_spin = QSpinBox()
        self.batch_spin.setMinimum(1)
        self.batch_spin.setMaximum(1000)
        self.batch_spin.setValue(50)
        self.batch_spin.setToolTip("每批处理的文件数量 (较大的批次可能会提高吞吐量)")
        performance_layout.addRow("批处理大小:", self.batch_spin)

        performance_group.setLayout(performance_layout)
        layout.addWidget(performance_group)

        # Buttons
        button_layout = QHBoxLayout()
        button_layout.addStretch()

        # OK and Cancel buttons
        button_box = QDialogButtonBox()
        button_box.setStandardButtons(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        button_layout.addWidget(button_box)

        layout.addLayout(button_layout)

        self.setLayout(layout)

    def _update_main_window_elements(self) -> None:
        """Update main window title and core elements."""
        self.main_window.setWindowTitle("文档扫描器")

        # Update window properties if needed
        if hasattr(self.main_window, "statusBar"):
            status_bar = self.main_window.statusBar()
            if status_bar:
                status_bar.setToolTip("当前应用程序状态")

    def _update_menu_elements(self) -> None:
        """Update all menu elements."""
        # Update menu bar
        if hasattr(self.main_window, "file_menu") and self.main_window.file_menu:
            self.main_window.file_menu.setTitle("文件 (&F)")

        if hasattr(self.main_window, "settings_menu") and self.main_window.settings_menu:
            self.main_window.settings_menu.setTitle("设置 (&S)")

        if hasattr(self.main_window, "help_menu") and self.main_window.help_menu:
            self.main_window.help_menu.setTitle("帮助 (&H)")

        # Update menu actions
        if hasattr(self.main_window, "save_action") and self.main_window.save_action:
            self.main_window.save_action.setText("保存结果")
            self.main_window.save_action.setToolTip("将扫描结果保存到文件")

        if hasattr(self.main_window, "clear_action") and self.main_window.clear_action:
            self.main_window.clear_action.setText("清除结果")
            self.main_window.clear_action.setToolTip("清除当前结果")

        if hasattr(self.main_window, "open_action") and self.main_window.open_action:
            self.main_window.open_action.setText("打开结果...")
            self.main_window.open_action.setToolTip("打开之前保存的结果")

        if hasattr(self.main_window, "preferences_action") and self.main_window.preferences_action:
            self.main_window.preferences_action.setText("首选项 (&P)...")

        if hasattr(self.main_window, "exit_action") and self.main_window.exit_action:
            self.main_window.exit_action.setText("退出 (&X)")

        if hasattr(self.main_window, "about_action") and self.main_window.about_action:
            self.main_window.about_action.setText("关于 (&A)")

    def _update_toolbar_elements(self) -> None:
        """Update toolbar elements if they exist."""
        # Toolbar updates would go here if toolbar is implemented

    def _update_status_elements(self) -> None:
        """Update status bar and other status elements."""
        if hasattr(self.main_window, "status_label") and self.main_window.status_label:
            # Update status label text based on current state
            current_text = self.main_window.status_label.text()
            if "Ready" in current_text or "准备" in current_text:
                self.main_window.status_label.setText("就绪")
            elif "Scanning" in current_text or "扫描" in current_text:
                self.main_window.status_label.setText("扫描中...")
            elif "Completed" in current_text or "完成" in current_text:
                self.main_window.status_label.setText("已完成")

    def _update_input_section_elements(self) -> None:
        """Update all elements in the input configuration section."""
        # Update group box titles
        self._update_group_box_titles()

        # Update input labels
        self._update_input_labels()

        # Update button texts
        self._update_input_buttons()

        # Update validation messages
        self._update_validation_elements()

    def _update_group_box_titles(self) -> None:
        """Update group box titles in the main layout."""
        central_widget = self.main_window.centralWidget()
        if not central_widget:
            return

        layout = central_widget.layout()
        if not layout:
            return

        for i in range(layout.count()):
            item = layout.itemAt(i)
            if item and item.widget() and isinstance(item.widget(), QGroupBox):
                group_box = item.widget()
                current_title = group_box.title()

                # Map current titles to new translations
                title_mapping = {
                    "Input Configuration": "输入配置",
                    "输入配置": "输入配置",
                    "Results": "结果",
                    "结果": "结果",
                }

                if current_title in title_mapping:
                    group_box.setTitle(title_mapping[current_title])

    def _update_input_labels(self) -> None:
        """Update input field labels."""
        # Update directory input label
        if hasattr(self.main_window, "dir_label") and self.main_window.dir_label:
            self.main_window.dir_label.setText("输入目录:")

        # Update rules file label
        if hasattr(self.main_window, "rules_label") and self.main_window.rules_label:
            self.main_window.rules_label.setText("规则文件:")

        # Update file types label
        if hasattr(self.main_window, "types_label") and self.main_window.types_label:
            self.main_window.types_label.setText("文件类型:")

    def _update_input_buttons(self) -> None:
        """Update input section buttons."""
        # Update browse buttons
        if hasattr(self.main_window, "browse_btn") and self.main_window.browse_btn:
            self.main_window.browse_btn.setText("浏览...")
            self.main_window.browse_btn.setToolTip("浏览选择输入目录")

        if hasattr(self.main_window, "browse_rules_btn") and self.main_window.browse_rules_btn:
            self.main_window.browse_rules_btn.setText("浏览...")
            self.main_window.browse_rules_btn.setToolTip("浏览选择规则文件")

    def _update_validation_elements(self) -> None:
        """Update validation-related UI elements."""
        if hasattr(self.main_window, "rules_validation_label") and self.main_window.rules_validation_label:
            # The validation label content stays the same (✓ or ✗)
            # But we ensure the styling is reapplied
            self.main_window.rules_validation_label.style().unpolish(self.main_window.rules_validation_label)
            self.main_window.rules_validation_label.style().polish(self.main_window.rules_validation_label)

    def _update_file_type_elements(self) -> None:
        """Update file type related UI elements including group combo and buttons."""
        # Update file type group combo box items
        if hasattr(self.main_window, "group_combo") and self.main_window.group_combo:
            # Store current selection
            current_text = self.main_window.group_combo.currentText()

            # Clear and repopulate with translated items
            self.main_window.group_combo.clear()
            group_items = [
                ("all_types_group", "📂 全部类型", "📂 All Types"),
                ("document_files_group", "📄 文档文件", "📄 Document Files"),
                ("spreadsheet_files_group", "📊 表格文件", "📊 Spreadsheet Files"),
                ("image_files_group", "🖼️ 图像文件", "🖼️ Image Files"),
                ("web_files_group", "🌐 网页文件", "🌐 Web Files"),
                ("archive_files_group", "📦 压缩文件", "📦 Archive Files"),
            ]

            for _key, zh_text, _en_text in group_items:
                display_text = zh_text  # Always use Chinese
                self.main_window.group_combo.addItem(display_text)

            # Restore selection if possible
            for i in range(self.main_window.group_combo.count()):
                if self.main_window.group_combo.itemText(i) == current_text:
                    self.main_window.group_combo.setCurrentIndex(i)
                    break

        # Update file type buttons text
        if hasattr(self.main_window, "add_type_btn") and self.main_window.add_type_btn:
            self.main_window.add_type_btn.setText("+ 添加类型")

        if hasattr(self.main_window, "remove_type_btn") and self.main_window.remove_type_btn:
            self.main_window.remove_type_btn.setText("- 移除类型")

    def _update_results_section_elements(self) -> None:  # noqa: C901
        """Update all elements in the results section."""
        # Update summary labels
        if hasattr(self.main_window, "files_label") and self.main_window.files_label:
            current_text = self.main_window.files_label.text()
            if "Files Scanned:" in current_text or "已扫描文件:" in current_text:
                # Preserve the numeric part but update the label
                parts = current_text.split()
                if len(parts) >= 2:  # noqa: PLR2004
                    count_part = parts[-1]  # Get the "current/total" part
                    self.main_window.files_label.setText(f"{'已扫描文件:'} {count_part}")
                else:
                    self.main_window.files_label.setText("已扫描文件：0")

        if hasattr(self.main_window, "matches_label") and self.main_window.matches_label:
            current_text = self.main_window.matches_label.text()
            if "Files with Matches:" in current_text or "包含匹配项的文件:" in current_text:
                # Extract and preserve the number
                import re

                match = re.search(r"(\d+)$", current_text)
                if match:
                    count = match.group(1)
                    self.main_window.matches_label.setText(f"{'包含匹配项的文件:'} {count}")
                else:
                    self.main_window.matches_label.setText("包含匹配项的文件：0")

        # Update section labels
        if hasattr(self.main_window, "log_label") and self.main_window.log_label:
            self.main_window.log_label.setText("进度日志:")

        if hasattr(self.main_window, "table_label") and self.main_window.table_label:
            self.main_window.table_label.setText("匹配详情:")

        if hasattr(self.main_window, "details_label") and self.main_window.details_label:
            self.main_window.details_label.setText("选中匹配项的上下文:")

        # Update table headers
        if hasattr(self.main_window, "results_table") and self.main_window.results_table:
            self.main_window.results_table.setHorizontalHeaderLabels(["文件", "类型", "匹配数", "时间 (s)"])

    def _update_action_buttons(self) -> None:
        """Update action buttons text and tooltips."""
        # Update main action buttons
        if hasattr(self.main_window, "scan_btn") and self.main_window.scan_btn:
            self.main_window.scan_btn.setText("开始扫描")
            self.main_window.scan_btn.setToolTip("开始文档扫描")

        if hasattr(self.main_window, "pause_btn") and self.main_window.pause_btn:
            # Preserve current state (Pause/Resume)
            current_text = self.main_window.pause_btn.text()
            if "Pause" in current_text or "暂停" in current_text:
                self.main_window.pause_btn.setText("暂停")
            else:
                self.main_window.pause_btn.setText("恢复")
            self.main_window.pause_btn.setToolTip("暂停或恢复扫描")

        if hasattr(self.main_window, "stop_btn") and self.main_window.stop_btn:
            self.main_window.stop_btn.setText("停止")
            self.main_window.stop_btn.setToolTip("MISSING:stop_tooltip")
