from PyQt6.QtWidgets import QLabel, QLineEdit, QComboBox, QDateEdit, QDateTimeEdit
from datetime import datetime


def highlight_invalid_field(widget, error_message):
    widget.setStyleSheet("border: 1px solid red;")
    widget.setToolTip(error_message)


def unhighlight_valid_field(widget):
    widget.setStyleSheet("")
    widget.setToolTip("")


# def validate_inputs(input_widgets, model):
#     validated_inputs = {}
#     valid = True

#     for key, widget in input_widgets.items():

#         if isinstance(widget, QLineEdit):
#             input_value = widget.text()

#         elif isinstance(widget, QComboBox):
#             input_value = (
#                 widget.currentText()
#             )  # For QComboBox, use currentText() to get the selected item
#         elif isinstance(widget, QDateEdit):
#             input_value = widget.date().toString(
#                 "dd.MM.yyyy"
#             )  # Format the QDate object to string as needed
#         else:
#             input_value = (
#                 None  # Handle other types or add more conditions for different widgets
#             )

#         is_field_valid, validated_value, error_message = model.validate_field(
#             key, input_value
#         )

#         if is_field_valid:
#             validated_inputs[key] = validated_value
#             unhighlight_valid_field(input_widgets[key])
#         else:
#             valid = False
#             highlight_invalid_field(input_widgets[key], error_message)

#     return valid, validated_inputs


def validate_inputs(input_widgets, validation_rules):
    validated_inputs = {}
    valid = True

    for key, widget in input_widgets.items():
        input_value = get_widget_value(widget)

        is_field_valid, validated_value, error_message = validate_field(
            key, input_value, validation_rules
        )

        if is_field_valid:
            validated_inputs[key] = validated_value
            unhighlight_valid_field(widget)
        else:
            valid = False
            highlight_invalid_field(widget, error_message)

    return valid, validated_inputs


def validate_field(key, input_value, validation_rules):
    try:
        rule = validation_rules.get(key)
        if not rule:
            return False, "No validation rule found."

        rule_type = rule["type"]
        if rule_type == "range":
            value = float(input_value)
            min_value, max_value = rule["min"], rule["max"]
            if rule["inclusive"] and not (min_value <= value <= max_value):
                raise ValueError(
                    f"Value must be between {min_value} and {max_value}, inclusive."
                )
            elif not rule["inclusive"] and not (min_value < value < max_value):
                raise ValueError(
                    f"Value must be between {min_value} and {max_value}, exclusive."
                )
        elif rule_type == "date":
            date_format = rule.get("format", "%Y-%m-%d")
            value = datetime.strptime(input_value, date_format).date()
        elif rule_type == "list":
            options = rule.get("options", [])
            if input_value not in options:
                raise ValueError(
                    f"Value must be one of the following: {', '.join(options)}"
                )
            value = input_value
        else:
            value = input_value  # Handle other types if necessary

        return True, value, ""
    except ValueError as e:
        return False, None, str(e)


def get_widget_value(widget):
    """
    Extracts and returns the value from the provided input widget.

    Parameters:
    - widget: The input widget from which to extract the value.

    Returns:
    - The value of the widget, properly formatted according to its type.
    """
    if isinstance(widget, QLineEdit):
        return widget.text()
    elif isinstance(widget, QComboBox):
        return widget.currentText()
    elif isinstance(widget, QDateEdit):
        # Extracts the date as a string in the specified format.
        return widget.date().toString("dd.MM.yyyy")
    elif isinstance(widget, QDateTimeEdit):
        # Extracts the date and time as a string in the specified format.
        return widget.dateTime().toString("dd.MM.yyyy HH:mm")
    # Extend this method to handle other widget types if necessary
    return None


def create_setting_field(parent, label_text, value):
    """
    Creates a label and a QLineEdit field with a specific label and initial value.

    Parameters:
    - parent: The parent widget to which these widgets belong.
    - label_text: The text to be displayed on the label.
    - value: The initial value to be displayed in the QLineEdit. If not set = None

    Returns:
    A tuple containing the created QLabel and QLineEdit.
    """
    label = QLabel(label_text, parent)
    input_field = QLineEdit(str(value), parent)
    return label, input_field
