package ui;

import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.util.StringConverter;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * Ein einfacher Spinner für Uhrzeiten im Format HH:mm.
 */
public class TimeSpinner extends Spinner<LocalTime> {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

    public TimeSpinner() {
        this(LocalTime.of(10, 0));
    }

    public TimeSpinner(LocalTime defaultTime) {
        setEditable(true);

        SpinnerValueFactory<LocalTime> factory = new SpinnerValueFactory<>() {
            {
                setValue(defaultTime);
            }

            @Override
            public void decrement(int steps) {
                LocalTime time = getValue() != null ? getValue() : LocalTime.of(10, 0);
                setValue(time.minusMinutes(steps * 5));
            }

            @Override
            public void increment(int steps) {
                LocalTime time = getValue() != null ? getValue() : LocalTime.of(10, 0);
                setValue(time.plusMinutes(steps * 5));
            }
        };

        factory.setConverter(new StringConverter<>() {
            @Override
            public String toString(LocalTime time) {
                return time == null ? "" : time.format(FORMATTER);
            }

            @Override
            public LocalTime fromString(String text) {
                try {
                    if (text == null || text.isBlank()) {
                        return getValue();
                    }

                    // Wenn Nutzer nur "10" oder "9" eintippt → ":00" ergänzen
                    String cleaned = text.trim();
                    if (cleaned.matches("^\\d{1,2}$")) {
                        cleaned = cleaned + ":00";
                    }

                    // Wenn z.B. "9:5" eingegeben wird → auf "09:05" normalisieren
                    if (cleaned.matches("^\\d{1,2}:\\d{1}$")) {
                        String[] parts = cleaned.split(":");
                        cleaned = String.format("%02d:%02d",
                                Integer.parseInt(parts[0]),
                                Integer.parseInt(parts[1]));
                    }

                    return LocalTime.parse(cleaned, FORMATTER);
                } catch (Exception e) {
                    return getValue();
                }
            }

        });

        setValueFactory(factory);
        getEditor().setText(defaultTime.format(FORMATTER));
    }
}
