from qgis.PyQt.QtWidgets import (QDockWidget, QWidget, QVBoxLayout, QHBoxLayout,
                                 QPushButton, QListWidget, QListWidgetItem,
                                 QComboBox, QLabel, QCheckBox, QLineEdit, QScrollArea, QGroupBox)
from qgis.PyQt.QtCore import Qt
from .translations import get_text, LANGUAGE_NAMES


class ALMonitorDockWidget(QDockWidget):
    def __init__(self, parent=None):
        super().__init__("AL Modify Monitor", parent)
        dock_area = getattr(Qt, 'DockWidgetArea', Qt)
        self.setAllowedAreas(dock_area.LeftDockWidgetArea | dock_area.RightDockWidgetArea)
        self.current_language = "en"

        # 主容器
        self.main_widget = QWidget()
        self.main_layout = QVBoxLayout(self.main_widget)

        language_layout = QHBoxLayout()
        self.combo_language = QComboBox()
        self.combo_language.setMaximumWidth(220)
        for lang_code, lang_name in LANGUAGE_NAMES:
            self.combo_language.addItem(lang_name, lang_code)
        language_layout.addWidget(self.combo_language)
        language_layout.addStretch()
        self.main_layout.addLayout(language_layout)

        # 1. 状态控制区
        self.toggle_btn = QPushButton("Start Tracking")
        self.toggle_btn.setCheckable(True)
        self.toggle_btn.setStyleSheet(
            "QPushButton:checked { background-color: #4CAF50; color: white; font-weight: bold; }")
        self.main_layout.addWidget(self.toggle_btn)

        self.btn_builtin_hotkeys = QPushButton("Enable Built-in Hotkeys")
        self.btn_builtin_hotkeys.setCheckable(True)
        self.btn_builtin_hotkeys.setStyleSheet(
            "QPushButton:checked { background-color: #2196F3; color: white; font-weight: bold; }")
        self.main_layout.addWidget(self.btn_builtin_hotkeys)

        # 2. 字段设置区
        field_layout = QHBoxLayout()
        self.label_field = QLabel("Status field:")
        field_layout.addWidget(self.label_field)
        self.combo_field = QComboBox()
        self.combo_field.setEditable(True)
        self.combo_field.setPlaceholderText("Leave empty to use al_checked")
        field_layout.addWidget(self.combo_field)
        self.main_layout.addLayout(field_layout)

        # ==================== 修改后 ====================
        # 3. 图层选择区 (带水平布局与刷新按钮)
        layer_header_layout = QHBoxLayout()
        self.label_layer_header = QLabel("Select vector layers to track:")
        layer_header_layout.addWidget(self.label_layer_header)
        layer_header_layout.addStretch()  # 弹簧，把按钮推到最右侧

        self.btn_refresh = QPushButton("Refresh Layers")  # 新增的刷新按钮
        # 给按钮一点样式，让它看起来更精致小巧
        self.btn_refresh.setStyleSheet("QPushButton { padding: 2px 8px; }")
        layer_header_layout.addWidget(self.btn_refresh)

        self.main_layout.addLayout(layer_header_layout)

        self.list_layers = QListWidget()
        self.main_layout.addWidget(self.list_layers)

        # 4. 快捷键配置区 (1~0)
        self.group_hotkeys = QGroupBox("Hotkey Configuration (active layer only)")
        hotkey_layout = QVBoxLayout()
        self.hotkey_configs = {}  # 存储快捷键UI组件的字典

        # 动态生成 1 到 0 的配置项
        keys = [str(i) for i in range(1, 10)] + ['0']
        for k in keys:
            row_layout = QHBoxLayout()
            chk_enable = QCheckBox(f"Key {k}")
            chk_enable.setChecked(k in ['1', '2'])  # 默认开启 1 和 2

            row_layout.addWidget(chk_enable)
            value_label = QLabel("Write value:")
            row_layout.addWidget(value_label)

            line_val = QLineEdit()
            # 默认值逻辑：1->1, 2->0, 其它->按键本身数字
            default_val = '1' if k == '1' else ('0' if k == '2' else k)
            line_val.setText(default_val)
            line_val.setMaximumWidth(80)
            row_layout.addWidget(line_val)

            hotkey_layout.addLayout(row_layout)
            self.hotkey_configs[k] = {
                'checkbox': chk_enable,
                'lineedit': line_val,
                'value_label': value_label
            }

        self.group_hotkeys.setLayout(hotkey_layout)

        # 使用 ScrollArea 包裹快捷键，防止小屏幕显示不全
        scroll = QScrollArea()
        scroll.setWidget(self.group_hotkeys)
        scroll.setWidgetResizable(True)
        self.main_layout.addWidget(scroll)

        self.setWidget(self.main_widget)

    def apply_language(self, language):
        self.current_language = language
        self.setWindowTitle(get_text(language, "dock_title"))

        self.combo_language.blockSignals(True)
        idx = self.combo_language.findData(language)
        if idx != -1:
            self.combo_language.setCurrentIndex(idx)
        self.combo_language.blockSignals(False)

        self.label_field.setText(get_text(language, "field_name"))
        self.combo_field.setPlaceholderText(get_text(language, "field_placeholder"))
        self.label_layer_header.setText(get_text(language, "layer_header"))
        self.btn_refresh.setText(get_text(language, "refresh_layers"))
        self.group_hotkeys.setTitle(get_text(language, "hotkey_group"))

        for key, cfg in self.hotkey_configs.items():
            cfg['checkbox'].setText(get_text(language, "key_label", key=key))
            cfg['value_label'].setText(get_text(language, "value_label"))

        self.update_action_button_texts()

    def update_action_button_texts(self):
        if self.toggle_btn.isChecked():
            self.toggle_btn.setText(get_text(self.current_language, "stop_tracking"))
        else:
            self.toggle_btn.setText(get_text(self.current_language, "start_tracking"))

        if self.btn_builtin_hotkeys.isChecked():
            self.btn_builtin_hotkeys.setText(get_text(self.current_language, "disable_builtin_hotkeys"))
        else:
            self.btn_builtin_hotkeys.setText(get_text(self.current_language, "enable_builtin_hotkeys"))