# File: components/i2c/i2c_command_editor.py

from PyQt6.QtWidgets import (
    QDialog,
    QVBoxLayout,
    QHBoxLayout,
    QLineEdit,
    QPushButton,
    QFormLayout,
    QComboBox,
    QSpinBox,
)
from PyQt6.QtCore import Qt


class I2CCommandEditorDialog(QDialog):
    def __init__(self, command=None):
        super().__init__()

        self.setWindowTitle("Modify I2C Command" if command else "Add I2C Command")

        form_layout = QFormLayout()
        form_layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
        form_layout.setFormAlignment(Qt.AlignmentFlag.AlignTop)
        form_layout.setSpacing(10)

        # === Input Fields ===
        self.name_input = QLineEdit()
        self.description_input = QLineEdit()
        self.category_input = QLineEdit()
        self.operation_input = QComboBox()
        self.operation_input.addItems(["read", "write"])
        self.register_input = QSpinBox()
        self.register_input.setRange(0, 255)
        self.hex_input = QLineEdit()
        self.hex_input.setPlaceholderText("0x01,0x02")

        if command:
            self.name_input.setText(command.get("name", ""))
            self.description_input.setText(command.get("description", ""))
            self.category_input.setText(command.get("category", ""))
            self.operation_input.setCurrentText(command.get("operation", "read"))
            self.register_input.setValue(command.get("register", 0))
            self.hex_input.setText(command.get("hex_string", ""))

        form_layout.addRow("Name:", self.name_input)
        form_layout.addRow("Description:", self.description_input)
        form_layout.addRow("Category:", self.category_input)
        form_layout.addRow("Operation:", self.operation_input)
        form_layout.addRow("Register:", self.register_input)
        form_layout.addRow("Hex:", self.hex_input)

        button_layout = QHBoxLayout()
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addStretch()
        button_layout.addWidget(self.ok_button)
        button_layout.addWidget(self.cancel_button)

        layout = QVBoxLayout(self)
        layout.addLayout(form_layout)
        layout.addLayout(button_layout)

        self.setMinimumWidth(400)

    def get_data(self):
        return {
            "name": self.name_input.text().strip(),
            "description": self.description_input.text().strip(),
            "category": self.category_input.text().strip(),
            "operation": self.operation_input.currentText(),
            "register": self.register_input.value(),
            "hex_string": self.hex_input.text().strip(),
        }
