package org.example.petshopdesktop.util;

import javafx.application.Platform;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;

import java.util.function.UnaryOperator;

public class TextFieldFormatSupport {

    /**
     * Applies a phone number formatter to a TextField.
     * The formatter only allows digits and automatically formats the input as (XXX) XXX-XXXX.
     *
     * @param textField The TextField to apply the formatter to.
     */
    public static void applyPhoneNumberFormat(TextField textField) {
        textField.textProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) return;

            // Remove all non-digit characters
            String digits = newValue.replaceAll("\\D", "");

            // Limit to 10 digits
            if (digits.length() > 10) {
                digits = digits.substring(0, 10);
            }

            StringBuilder formatted = new StringBuilder();
            int len = digits.length();

            if (len > 0) {
                formatted.append("(");
                if (len <= 3) {
                    formatted.append(digits);
                } else {
                    formatted.append(digits, 0, 3).append(") ");
                    if (len <= 6) {
                        formatted.append(digits.substring(3));
                    } else {
                        formatted.append(digits, 3, 6).append("-").append(digits.substring(6));
                    }
                }
            }

            String result = formatted.toString();
            if (!result.equals(newValue)) {
                Platform.runLater(() -> {
                    textField.setText(result);
                    textField.positionCaret(result.length());
                });
            }
        });
    }
}
