from PySide6.QtWidgets import QWidget, QLineEdit, QLabel, QHBoxLayout, QVBoxLayout, QSizePolicy
from PySide6.QtCore import Qt, Signal


class ValidationInput(QWidget):
    textChanged = Signal(str)

    def __init__(self, placeholder_text="", is_password=False):
        super().__init__()
        self.validator = None
        self.is_valid = False
        self.is_required = True

        self.main_layout = QVBoxLayout(self)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(5)

        input_layout = QHBoxLayout()
        self.input = QLineEdit()
        self.input.setPlaceholderText(placeholder_text)
        self.input.setFixedHeight(40)
        if is_password:
            self.input.setEchoMode(QLineEdit.Password)
        
        # self.status_label = QLabel()
        # self.status_label.setFixedSize(20, 20)
        # self.status_label.setAlignment(Qt.AlignCenter)
        # font = self.status_label.font()
        # font.setPointSize(14)
        # self.status_label.setFont(font)

        input_layout.addWidget(self.input)
        # input_layout.addWidget(self.status_label)

        self.error_label = QLabel()
        self.error_label.setWordWrap(True)
        self.error_label.setStyleSheet("color: red; font-size: 12px;")
        self.error_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.error_label.hide()

        self.main_layout.addLayout(input_layout)
        self.main_layout.addWidget(self.error_label)

        self.input.textChanged.connect(self.on_text_changed)

    def set_validator(self, validator, is_required=True):
        self.validator = validator
        self.is_required = is_required

    def on_text_changed(self, text):
        self.textChanged.emit(text)
        if not self.validator:
            return

        if not self.is_required and not text:
            self.is_valid = True
            # self.status_label.clear()
            self.error_label.hide()
            return

        is_valid, message = self.validator(text)
        self.is_valid = is_valid
        if is_valid:
            # self.status_label.setText("✓")
            # self.status_label.setStyleSheet("color: green;")
            self.error_label.hide()
        else:
            # self.status_label.setText("✗")
            # self.status_label.setStyleSheet("color: red;")
            self.error_label.setText(message)
            self.error_label.show()

    def text(self):
        return self.input.text()

    def setText(self, text):
        self.input.setText(text)

    def clear(self):
        self.input.clear()
        # self.status_label.clear()
        self.error_label.hide()
        self.is_valid = False
