package top.r3944realms.docchecktoolrefactored.ui.utils;

import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import top.r3944realms.docchecktoolrefactored.Main;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 进度条窗口工具类，支持取消按钮
 */
public class ProgressBar {

    private Stage progressStage;
    private javafx.scene.control.ProgressBar progressBar;
    private Label messageLabel;
    private Button cancelButton;
    private final boolean isCancelable;
    private final AtomicBoolean cancelled = new AtomicBoolean(false);
    private Runnable onCancelCallback;

    // 进度条窗口图标
    private static final Image PROGRESS_ICON;

    // CSS样式路径
    private static final String PROGRESS_CSS;

    static {
        // 初始化图标和CSS路径
        PROGRESS_ICON = new Image(Objects.requireNonNull(
                Main.class.getResourceAsStream("/img/logo256x.ico")
        ));
        PROGRESS_CSS = Objects.requireNonNull(
                Main.class.getResource("/css/inner/progress.css")
        ).toExternalForm();
    }

    public ProgressBar(boolean isCancelable) {
        this.isCancelable = isCancelable;
    }

    public ProgressBar() {
        this(true);
    }

    /**
     * 显示进度条窗口
     * @param ownerStage 父窗口
     * @param title 窗口标题
     * @param initialMessage 初始消息
     */
    public void showProgress(Stage ownerStage, String title, String initialMessage) {
        Platform.runLater(() -> {
            progressStage = new Stage();
            progressStage.initOwner(ownerStage);
            progressStage.initStyle(StageStyle.UTILITY);

            // 设置窗口图标
            progressStage.getIcons().add(PROGRESS_ICON);

            if (isCancelable) {
                progressStage.setOnCloseRequest(windowEvent -> {
                    if (!DialogUtil.showCancelConfirmation(progressStage.getOwner())) {
                        windowEvent.consume();
                    }
                    else {
                        cancelled.set(true);
                        if (onCancelCallback != null) {
                            onCancelCallback.run();
                        }
                        closeProgress();
                    }
                });
            }
            progressStage.initModality(Modality.APPLICATION_MODAL);
            progressStage.setTitle(title);
            progressStage.setResizable(false);

            // 创建进度条
            progressBar = new javafx.scene.control.ProgressBar();
            progressBar.setPrefWidth(300);
            progressBar.setProgress(javafx.scene.control.ProgressBar.INDETERMINATE_PROGRESS);

            // 创建消息标签
            messageLabel = new Label(initialMessage);

            if (isCancelable) {
                // 创建取消按钮
                cancelButton = new Button("取消");
                cancelButton.setOnAction(e -> {
                    cancelled.set(true);
                    if (onCancelCallback != null) {
                        onCancelCallback.run();
                    }
                    closeProgress();
                });

                // 如果 setOnCancel 先调用过，绑定回调
                if (onCancelCallback != null) {
                    cancelButton.setOnAction(e -> {
                        cancelled.set(true);
                        onCancelCallback.run();
                        closeProgress();
                    });
                }
            }

            // 布局
            VBox root = new VBox(15, messageLabel, progressBar);
            root.getStyleClass().add("vbox"); // 添加样式类
            if (isCancelable) {
                root.getChildren().add(cancelButton);
            }

            // 应用CSS样式
            Scene scene = new Scene(root);
            scene.getStylesheets().add(PROGRESS_CSS);

            progressStage.setScene(scene);
            progressStage.sizeToScene();
            progressStage.centerOnScreen(); // 居中显示
            progressStage.show();
        });
    }

    /**
     * 更新进度和消息
     * @param progress 进度值 (0.0 - 1.0)
     * @param message 要显示的消息
     */
    public void updateProgress(double progress, String message) {
        Platform.runLater(() -> {
            if (progressBar != null) {
                progressBar.setProgress(progress);
            }
            if (messageLabel != null) {
                messageLabel.setText(message);
            }
        });
    }

    /**
     * 关闭进度条窗口
     */
    public void closeProgress() {
        Platform.runLater(() -> {
            if (progressStage != null) {
                progressStage.close();
            }
        });
    }

    /**
     * 是否已取消
     */
    public boolean isCancelled() {
        return cancelled.get();
    }

    /**
     * 快速显示一个进度条窗口并执行任务
     * @param ownerStage 父窗口
     * @param title 窗口标题
     * @param initialMessage 初始消息
     * @param task 要执行的任务（可检查 isCancelled() 中途退出）
     */
    public static void showAndExecute(Stage ownerStage, String title, String initialMessage, CancellableTask task) {
        ProgressBar progressBar = new ProgressBar();
        progressBar.showProgress(ownerStage, title, initialMessage);

        new Thread(() -> {
            try {
                task.run(progressBar);
            } finally {
                progressBar.closeProgress();
            }
        }).start();
    }

    @FunctionalInterface
    public interface CancellableTask {
        void run(ProgressBar util);
    }

    public void setOnCancel(Runnable onCancel) {
        if (isCancelable) {
            if (cancelButton != null) {
                cancelButton.setOnAction(e -> {
                    cancelled.set(true);
                    if (onCancel != null) {
                        onCancel.run();
                    }
                    closeProgress();
                });
            } else {
                // 保存回调，稍后在按钮创建后绑定
                this.onCancelCallback = onCancel;
            }
        } else throw new UnsupportedOperationException("Cancellable task is not supported");
    }
}
