"""Settings view component."""

from __future__ import annotations

from typing import TYPE_CHECKING

from PySide2.QtWidgets import (
    QCheckBox,
    QComboBox,
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QSpinBox,
    QTabWidget,
    QTextEdit,
    QVBoxLayout,
    QWidget,
)

if TYPE_CHECKING:
    from pytola_sim.lscsim.core.main_controller import MainController


class SettingsView(QWidget):
    """Settings view component."""

    def __init__(self, controller: MainController) -> None:
        super().__init__()
        self.controller = controller
        self._setup_ui()

    def _setup_ui(self) -> None:
        main_layout = QVBoxLayout(self)

        # Create tab widget
        self.tab_widget = QTabWidget()

        # General settings tab
        self.general_tab = self._create_general_tab()
        self.tab_widget.addTab(self.general_tab, "常规设置")

        # Paths settings tab
        self.paths_tab = self._create_paths_tab()
        self.tab_widget.addTab(self.paths_tab, "路径设置")

        # Solver settings tab
        self.solver_tab = self._create_solver_tab()
        self.tab_widget.addTab(self.solver_tab, "求解器设置")

        # Display settings tab
        self.display_tab = self._create_display_tab()
        self.tab_widget.addTab(self.display_tab, "显示设置")

        # Security settings tab
        self.security_tab = self._create_security_tab()
        self.tab_widget.addTab(self.security_tab, "安全设置")

        main_layout.addWidget(self.tab_widget)

        # Control buttons
        button_layout = QHBoxLayout()
        self.apply_btn = QPushButton("应用设置")
        self.ok_btn = QPushButton("确定")
        self.cancel_btn = QPushButton("取消")
        self.reset_btn = QPushButton("恢复默认")

        # Style buttons
        self.apply_btn.setStyleSheet("background-color: #4CAF50; color: white;")
        self.ok_btn.setStyleSheet("background-color: #2196F3; color: white;")
        self.cancel_btn.setStyleSheet("background-color: #F44336; color: white;")
        self.reset_btn.setStyleSheet("background-color: #FF9800; color: white;")

        button_layout.addWidget(self.apply_btn)
        button_layout.addWidget(self.ok_btn)
        button_layout.addWidget(self.cancel_btn)
        button_layout.addWidget(self.reset_btn)
        button_layout.addStretch()

        main_layout.addLayout(button_layout)

        # Connect signals
        self._connect_signals()

    def _create_general_tab(self) -> QWidget:
        """Create general settings tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Language and theme
        appearance_group = QGroupBox("外观设置")
        appearance_layout = QFormLayout(appearance_group)

        self.language_combo = QComboBox()
        self.language_combo.addItems(["中文 (简体)", "English"])
        self.language_combo.setCurrentIndex(0)  # Default to Chinese

        self.theme_combo = QComboBox()
        self.theme_combo.addItems(["默认主题", "深色主题", "浅色主题"])

        appearance_layout.addRow("语言:", self.language_combo)
        appearance_layout.addRow("主题:", self.theme_combo)

        layout.addWidget(appearance_group)

        # Auto-save settings
        autosave_group = QGroupBox("自动保存")
        autosave_layout = QVBoxLayout(autosave_group)

        self.autosave_checkbox = QCheckBox("启用自动保存")
        self.autosave_checkbox.setChecked(True)

        autosave_interval_layout = QHBoxLayout()
        self.autosave_interval_spin = QSpinBox()
        self.autosave_interval_spin.setRange(30, 3600)
        self.autosave_interval_spin.setValue(300)
        self.autosave_interval_spin.setSuffix(" 秒")

        autosave_interval_layout.addWidget(QLabel("自动保存间隔:"))
        autosave_interval_layout.addWidget(self.autosave_interval_spin)
        autosave_interval_layout.addStretch()

        autosave_layout.addWidget(self.autosave_checkbox)
        autosave_layout.addLayout(autosave_interval_layout)

        layout.addWidget(autosave_group)

        # Recent files
        recent_group = QGroupBox("最近文件")
        recent_layout = QHBoxLayout(recent_group)

        self.recent_files_spin = QSpinBox()
        self.recent_files_spin.setRange(0, 50)
        self.recent_files_spin.setValue(10)

        recent_layout.addWidget(QLabel("保留最近文件数量:"))
        recent_layout.addWidget(self.recent_files_spin)
        recent_layout.addStretch()

        layout.addWidget(recent_group)
        layout.addStretch()

        return widget

    def _create_paths_tab(self) -> QWidget:
        """Create paths settings tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Working directories
        working_group = QGroupBox("工作目录")
        working_layout = QFormLayout(working_group)

        self.working_dir_edit = QLineEdit()
        self.working_dir_edit.setText("~/LSCSIM_Work")
        self.browse_working_btn = QPushButton("浏览")

        self.temp_dir_edit = QLineEdit()
        self.temp_dir_edit.setText("~/LSCSIM_Temp")
        self.browse_temp_btn = QPushButton("浏览")

        self.results_dir_edit = QLineEdit()
        self.results_dir_edit.setText("~/LSCSIM_Results")
        self.browse_results_btn = QPushButton("浏览")

        working_layout.addRow(
            "工作目录:",
            self._create_path_widget(self.working_dir_edit, self.browse_working_btn),
        )
        working_layout.addRow(
            "临时目录:",
            self._create_path_widget(self.temp_dir_edit, self.browse_temp_btn),
        )
        working_layout.addRow(
            "结果目录:",
            self._create_path_widget(self.results_dir_edit, self.browse_results_btn),
        )

        layout.addWidget(working_group)

        # Software paths
        software_group = QGroupBox("软件路径")
        software_layout = QFormLayout(software_group)

        self.solver_path_edit = QLineEdit()
        self.solver_path_edit.setText("C:/Program Files/LS-DYNA")
        self.browse_solver_btn = QPushButton("浏览")

        self.post_path_edit = QLineEdit()
        self.post_path_edit.setText("C:/Program Files/LSTC/LS-PrePost")
        self.browse_post_btn = QPushButton("浏览")

        software_layout.addRow(
            "求解器路径:",
            self._create_path_widget(self.solver_path_edit, self.browse_solver_btn),
        )
        software_layout.addRow(
            "后处理路径:",
            self._create_path_widget(self.post_path_edit, self.browse_post_btn),
        )

        layout.addWidget(software_group)

        # Validation button
        self.validate_paths_btn = QPushButton("验证路径")
        layout.addWidget(self.validate_paths_btn)

        # Validation results
        self.validation_results = QTextEdit()
        self.validation_results.setMaximumHeight(100)
        self.validation_results.setReadOnly(True)
        self.validation_results.setPlaceholderText("路径验证结果将在此显示...")

        layout.addWidget(self.validation_results)
        layout.addStretch()

        return widget

    def _create_solver_tab(self) -> QWidget:
        """Create solver settings tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Solver selection
        solver_group = QGroupBox("求解器配置")
        solver_layout = QFormLayout(solver_group)

        self.default_solver_combo = QComboBox()
        self.default_solver_combo.addItems(["LS-DYNA", "Abaqus", "ANSYS"])

        solver_layout.addRow("默认求解器:", self.default_solver_combo)

        layout.addWidget(solver_group)

        # Resource allocation
        resource_group = QGroupBox("资源分配")
        resource_layout = QFormLayout(resource_group)

        self.max_cores_spin = QSpinBox()
        self.max_cores_spin.setRange(1, 64)
        self.max_cores_spin.setValue(8)

        self.memory_limit_spin = QSpinBox()
        self.memory_limit_spin.setRange(1, 256)
        self.memory_limit_spin.setValue(16)
        self.memory_limit_spin.setSuffix(" GB")

        resource_layout.addRow("最大CPU核心数:", self.max_cores_spin)
        resource_layout.addRow("内存限制:", self.memory_limit_spin)

        layout.addWidget(resource_group)

        # License settings
        license_group = QGroupBox("许可证设置")
        license_layout = QVBoxLayout(license_group)

        self.license_check_checkbox = QCheckBox("启用许可证检查")
        self.license_check_checkbox.setChecked(True)

        license_server_layout = QHBoxLayout()
        self.license_server_edit = QLineEdit()
        self.license_server_edit.setText("localhost")
        self.test_license_btn = QPushButton("测试连接")

        license_server_layout.addWidget(QLabel("许可证服务器:"))
        license_server_layout.addWidget(self.license_server_edit)
        license_server_layout.addWidget(self.test_license_btn)

        license_layout.addWidget(self.license_check_checkbox)
        license_layout.addLayout(license_server_layout)

        layout.addWidget(license_group)

        # Test connection results
        self.connection_results = QTextEdit()
        self.connection_results.setMaximumHeight(80)
        self.connection_results.setReadOnly(True)
        self.connection_results.setPlaceholderText("连接测试结果将在此显示...")

        layout.addWidget(self.connection_results)
        layout.addStretch()

        return widget

    def _create_display_tab(self) -> QWidget:
        """Create display settings tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Graphics settings
        graphics_group = QGroupBox("图形渲染")
        graphics_layout = QFormLayout(graphics_group)

        self.graphics_backend_combo = QComboBox()
        self.graphics_backend_combo.addItems(["OpenGL", "DirectX", "Software"])

        self.render_quality_combo = QComboBox()
        self.render_quality_combo.addItems(["低质量", "中等质量", "高质量", "超高质量"])

        self.anti_aliasing_checkbox = QCheckBox("启用抗锯齿")
        self.anti_aliasing_checkbox.setChecked(True)

        graphics_layout.addRow("图形后端:", self.graphics_backend_combo)
        graphics_layout.addRow("渲染质量:", self.render_quality_combo)
        graphics_layout.addRow(self.anti_aliasing_checkbox)

        layout.addWidget(graphics_group)

        # Visualization settings
        vis_group = QGroupBox("可视化选项")
        vis_layout = QVBoxLayout(vis_group)

        self.wireframe_checkbox = QCheckBox("线框模式")
        self.shading_checkbox = QCheckBox("着色显示")
        self.shading_checkbox.setChecked(True)
        self.axis_indicator_checkbox = QCheckBox("坐标轴指示器")
        self.axis_indicator_checkbox.setChecked(True)

        vis_layout.addWidget(self.wireframe_checkbox)
        vis_layout.addWidget(self.shading_checkbox)
        vis_layout.addWidget(self.axis_indicator_checkbox)

        layout.addWidget(vis_group)

        # Performance settings
        perf_group = QGroupBox("性能设置")
        perf_layout = QFormLayout(perf_group)

        self.cache_size_spin = QSpinBox()
        self.cache_size_spin.setRange(128, 8192)
        self.cache_size_spin.setValue(1024)
        self.cache_size_spin.setSuffix(" MB")

        self.fps_limit_spin = QSpinBox()
        self.fps_limit_spin.setRange(30, 120)
        self.fps_limit_spin.setValue(60)

        perf_layout.addRow("缓存大小:", self.cache_size_spin)
        perf_layout.addRow("帧率限制:", self.fps_limit_spin)

        layout.addWidget(perf_group)
        layout.addStretch()

        return widget

    def _create_security_tab(self) -> QWidget:
        """Create security settings tab."""
        widget = QWidget()
        layout = QVBoxLayout(widget)

        # Authentication
        auth_group = QGroupBox("身份验证")
        auth_layout = QVBoxLayout(auth_group)

        self.password_required_checkbox = QCheckBox("需要密码保护")
        self.password_required_checkbox.setChecked(False)

        self.audit_logging_checkbox = QCheckBox("启用审计日志")
        self.audit_logging_checkbox.setChecked(True)

        auth_layout.addWidget(self.password_required_checkbox)
        auth_layout.addWidget(self.audit_logging_checkbox)

        layout.addWidget(auth_group)

        # Data protection
        data_group = QGroupBox("数据保护")
        data_layout = QVBoxLayout(data_group)

        self.data_encryption_checkbox = QCheckBox("启用数据加密")
        self.backup_enabled_checkbox = QCheckBox("启用自动备份")
        self.backup_enabled_checkbox.setChecked(True)

        backup_layout = QHBoxLayout()
        self.backup_interval_spin = QSpinBox()
        self.backup_interval_spin.setRange(1, 1440)
        self.backup_interval_spin.setValue(60)
        self.backup_interval_spin.setSuffix(" 分钟")

        backup_layout.addWidget(QLabel("备份间隔:"))
        backup_layout.addWidget(self.backup_interval_spin)
        backup_layout.addStretch()

        data_layout.addWidget(self.data_encryption_checkbox)
        data_layout.addWidget(self.backup_enabled_checkbox)
        data_layout.addLayout(backup_layout)

        layout.addWidget(data_group)

        # Network security
        network_group = QGroupBox("网络安全")
        network_layout = QVBoxLayout(network_group)

        self.firewall_integration_checkbox = QCheckBox("防火墙集成")
        self.secure_connections_checkbox = QCheckBox("安全连接")
        self.secure_connections_checkbox.setChecked(True)

        network_layout.addWidget(self.firewall_integration_checkbox)
        network_layout.addWidget(self.secure_connections_checkbox)

        layout.addWidget(network_group)

        # Security status
        status_group = QGroupBox("安全状态")
        status_layout = QVBoxLayout(status_group)

        self.security_status = QTextEdit()
        self.security_status.setMaximumHeight(100)
        self.security_status.setReadOnly(True)
        self.security_status.setText(
            "安全状态良好\n• 访问控制: 启用\n• 日志记录: 启用\n• 自动备份: 启用",
        )

        status_layout.addWidget(self.security_status)

        layout.addWidget(status_group)
        layout.addStretch()

        return widget

    def _create_path_widget(
        self,
        line_edit: QLineEdit,
        browse_button: QPushButton,
    ) -> QWidget:
        """Create a widget containing a line edit and browse button."""
        widget = QWidget()
        layout = QHBoxLayout(widget)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(line_edit)
        layout.addWidget(browse_button)
        return widget

    def _connect_signals(self) -> None:
        """Connect UI signals to slots."""
        # Button signals
        self.apply_btn.clicked.connect(self._on_apply_settings)
        self.ok_btn.clicked.connect(self._on_ok)
        self.cancel_btn.clicked.connect(self._on_cancel)
        self.reset_btn.clicked.connect(self._on_reset_defaults)
        self.validate_paths_btn.clicked.connect(self._on_validate_paths)
        self.test_license_btn.clicked.connect(self._on_test_license)

        # Browse button signals
        self.browse_working_btn.clicked.connect(
            lambda: self._browse_directory(self.working_dir_edit),
        )
        self.browse_temp_btn.clicked.connect(
            lambda: self._browse_directory(self.temp_dir_edit),
        )
        self.browse_results_btn.clicked.connect(
            lambda: self._browse_directory(self.results_dir_edit),
        )
        self.browse_solver_btn.clicked.connect(
            lambda: self._browse_directory(self.solver_path_edit),
        )
        self.browse_post_btn.clicked.connect(
            lambda: self._browse_directory(self.post_path_edit),
        )

    def _browse_directory(self, line_edit: QLineEdit) -> None:
        """Open directory browser dialog."""
        from PySide2.QtWidgets import QFileDialog

        directory = QFileDialog.getExistingDirectory(self, "选择目录", line_edit.text())
        if directory:
            line_edit.setText(directory)

    def _on_apply_settings(self) -> None:
        """Handle apply settings button click."""
        settings = self._collect_settings()
        self.controller.execute_command("Settings.UpdateSetting", settings)

    def _on_ok(self) -> None:
        """Handle OK button click."""
        self._on_apply_settings()
        # Close dialog or parent window
        self.window().close()

    def _on_cancel(self) -> None:
        """Handle cancel button click."""
        # Close dialog or parent window
        self.window().close()

    def _on_reset_defaults(self) -> None:
        """Handle reset defaults button click."""
        self.controller.execute_command("Settings.ResetSettings")
        # Reset UI to default values
        self._reset_ui_to_defaults()

    def _on_validate_paths(self) -> None:
        """Handle validate paths button click."""
        paths = {
            "working_dir": self.working_dir_edit.text(),
            "temp_dir": self.temp_dir_edit.text(),
            "results_dir": self.results_dir_edit.text(),
            "solver_path": self.solver_path_edit.text(),
            "post_path": self.post_path_edit.text(),
        }

        self.controller.execute_command("Settings.ValidatePaths", paths)

        # Simulate validation results
        self.validation_results.setText(
            "路径验证完成:\n"
            "✓ 工作目录: 可访问\n"
            "✓ 临时目录: 可访问\n"
            "✓ 结果目录: 可访问\n"
            "✓ 求解器路径: 存在\n"
            "✓ 后处理路径: 存在",
        )

    def _on_test_license(self) -> None:
        """Handle test license button click."""
        server = self.license_server_edit.text()
        self.controller.execute_command(
            "Settings.TestConnections",
            {"license_server": server},
        )

        # Simulate connection test
        self.connection_results.setText(
            f"许可证服务器连接测试:\n服务器: {server}\n状态: 连接成功\n响应时间: 45ms\n许可证数量: 8 可用",
        )

    def _collect_settings(self) -> dict:
        """Collect all settings from UI controls."""
        return {
            "general": {
                "language": self.language_combo.currentText(),
                "theme": self.theme_combo.currentText(),
                "auto_save": self.autosave_checkbox.isChecked(),
                "auto_save_interval": self.autosave_interval_spin.value(),
                "recent_files_count": self.recent_files_spin.value(),
            },
            "paths": {
                "working_directory": self.working_dir_edit.text(),
                "temp_directory": self.temp_dir_edit.text(),
                "results_directory": self.results_dir_edit.text(),
                "solver_path": self.solver_path_edit.text(),
                "post_path": self.post_path_edit.text(),
            },
            "solver": {
                "default_solver": self.default_solver_combo.currentText(),
                "max_cores": self.max_cores_spin.value(),
                "memory_limit_gb": self.memory_limit_spin.value(),
                "license_check": self.license_check_checkbox.isChecked(),
                "license_server": self.license_server_edit.text(),
            },
            "display": {
                "graphics_backend": self.graphics_backend_combo.currentText(),
                "render_quality": self.render_quality_combo.currentText(),
                "anti_aliasing": self.anti_aliasing_checkbox.isChecked(),
                "wireframe": self.wireframe_checkbox.isChecked(),
                "shading": self.shading_checkbox.isChecked(),
                "axis_indicator": self.axis_indicator_checkbox.isChecked(),
                "cache_size_mb": self.cache_size_spin.value(),
                "fps_limit": self.fps_limit_spin.value(),
            },
            "security": {
                "password_required": self.password_required_checkbox.isChecked(),
                "audit_logging": self.audit_logging_checkbox.isChecked(),
                "data_encryption": self.data_encryption_checkbox.isChecked(),
                "backup_enabled": self.backup_enabled_checkbox.isChecked(),
                "backup_interval_minutes": self.backup_interval_spin.value(),
                "firewall_integration": self.firewall_integration_checkbox.isChecked(),
                "secure_connections": self.secure_connections_checkbox.isChecked(),
            },
        }

    def _reset_ui_to_defaults(self) -> None:
        """Reset UI controls to default values."""
        # General tab defaults
        self.language_combo.setCurrentIndex(0)
        self.theme_combo.setCurrentIndex(0)
        self.autosave_checkbox.setChecked(True)
        self.autosave_interval_spin.setValue(300)
        self.recent_files_spin.setValue(10)

        # Paths tab defaults
        self.working_dir_edit.setText("~/LSCSIM_Work")
        self.temp_dir_edit.setText("~/LSCSIM_Temp")
        self.results_dir_edit.setText("~/LSCSIM_Results")
        self.solver_path_edit.setText("C:/Program Files/LS-DYNA")
        self.post_path_edit.setText("C:/Program Files/LSTC/LS-PrePost")

        # Solver tab defaults
        self.default_solver_combo.setCurrentIndex(0)
        self.max_cores_spin.setValue(8)
        self.memory_limit_spin.setValue(16)
        self.license_check_checkbox.setChecked(True)
        self.license_server_edit.setText("localhost")

        # Display tab defaults
        self.graphics_backend_combo.setCurrentIndex(0)
        self.render_quality_combo.setCurrentIndex(2)
        self.anti_aliasing_checkbox.setChecked(True)
        self.wireframe_checkbox.setChecked(False)
        self.shading_checkbox.setChecked(True)
        self.axis_indicator_checkbox.setChecked(True)
        self.cache_size_spin.setValue(1024)
        self.fps_limit_spin.setValue(60)

        # Security tab defaults
        self.password_required_checkbox.setChecked(False)
        self.audit_logging_checkbox.setChecked(True)
        self.data_encryption_checkbox.setChecked(False)
        self.backup_enabled_checkbox.setChecked(True)
        self.backup_interval_spin.setValue(60)
        self.firewall_integration_checkbox.setChecked(False)
        self.secure_connections_checkbox.setChecked(True)
