# File: components/uart/uart_command_editor.py

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


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

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

        # === Create form layout for consistent label alignment ===
        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.category_input = QLineEdit()
        self.description_input = QLineEdit()
        self.hex_input = QLineEdit()

        # === Prefill if modifying ===
        if command:
            self.name_input.setText(command.get("name", ""))
            self.category_input.setText(command.get("category", ""))
            self.description_input.setText(command.get("description", ""))
            self.hex_input.setText(
                command.get("hex_string", command.get("hex_string", ""))
            )

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

        # === Buttons ===
        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)

        # === Final layout ===
        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(),
            "category": self.category_input.text().strip(),
            "hex_string": self.hex_input.text().strip(),
            "description": self.description_input.text().strip(),
        }
