package org.example.petshopdesktop.util;

import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.animation.PauseTransition;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.Label;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseButton;
import javafx.util.Duration;

import java.text.NumberFormat;
import java.util.Locale;
import java.util.function.Consumer;

public final class TableViewSupport {

    private TableViewSupport() {
    }

    public static <T> void bindSortedItems(TableView<T> tableView, FilteredList<T> filteredItems) {
        SortedList<T> sortedItems = new SortedList<>(filteredItems);
        sortedItems.comparatorProperty().bind(tableView.comparatorProperty());
        tableView.setItems(sortedItems);
    }

    public static void clearSort(TableView<?> tableView) {
        tableView.getSortOrder().clear();
    }

    public static void flashStatus(Label label, String message) {
        if (label == null) {
            return;
        }
        label.setText(message);
        label.setVisible(true);
        PauseTransition delay = new PauseTransition(Duration.seconds(1.5));
        delay.setOnFinished(event -> {
            label.setVisible(false);
        });
        delay.playFromStart();
    }

    public static <S, T extends Number> void applyCurrencyColumn(TableColumn<S, T> column) {
        if (column == null) {
            return;
        }
        column.setCellFactory(col -> new TableCell<>() {
            private final NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CANADA);

            @Override
            protected void updateItem(T value, boolean empty) {
                super.updateItem(value, empty);
                setText(empty || value == null ? null : currency.format(value.doubleValue()));
            }
        });
    }

    public static <T> void installDoubleClickAction(TableView<T> tableView, Consumer<T> action) {
        tableView.setRowFactory(tv -> {
            TableRow<T> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2 && !row.isEmpty()) {
                    action.accept(row.getItem());
                }
            });
            return row;
        });
    }
}
