package top.r3944realms.docchecktoolrefactored.ui.utils;

import javafx.application.Platform;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.docchecktoolrefactored.Main;

import java.util.Optional;
import java.util.Objects;

/**
 * 对话框工具类
 */
public class DialogUtil {
    // -------------------------- 1. 全局CSS路径定义 --------------------------
    // 定义dialog-util.css的资源路径（需与项目中CSS文件实际路径一致）
    private static final String DIALOG_CSS_PATH = Objects.requireNonNull(
            Main.class.getResource("/css/inner/dialog.css")
    ).toExternalForm();

    private static final Image DIALOG_ICON = new Image(
            Objects.requireNonNull(Main.class.getResourceAsStream("/img/icon.jpg"))
    );
    /**
     * Show exit confirmation boolean.
     *
     * @param owner the owner
     * @return the boolean
     */
    public static boolean showExitConfirmation(Window owner) {
        return showConfirmationDialog("确认退出", "您确定要退出程序吗？", "请确认您的操作");
    }

    /**
     * Show exit confirmation boolean.
     *
     * @param owner the owner
     * @return the boolean
     */
    public static boolean showCancelConfirmation(Window owner) {
        return showConfirmationDialog("确认取消", "您确定要取消该任务吗？", "请确认您的操作");
    }

    /**
     * Show confirmation dialog boolean.
     *
     * @param title   the title
     * @param header  the header
     * @param content the content
     * @return the boolean
     */
    public static boolean showConfirmationDialog(String title, String header, String content) {
        // 创建确认对话框
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        // -------------------------- 2. 绑定CSS + 添加类型标识 --------------------------
        bindDialogCss(alert, Alert.AlertType.CONFIRMATION);
        setAlertIcon(alert);

        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        ButtonType yesButton = new ButtonType("是", ButtonBar.ButtonData.YES);
        ButtonType noButton = new ButtonType("否", ButtonBar.ButtonData.NO);
        alert.getButtonTypes().setAll(yesButton, noButton);

        Optional<ButtonType> result = alert.showAndWait();
        return result.isPresent() && result.get() == yesButton;
    }

    /**
     * Show information dialog.
     *
     * @param title   the title
     * @param header  the header
     * @param content the content
     */
    public static void showInformationDialog(String title, String header, String content) {
        Platform.runLater(() -> {
            Alert alert = createAlert(Alert.AlertType.INFORMATION, title, header, content);
            setAlertIcon(alert);
            alert.showAndWait();
        });
    }

    /**
     * Show warning dialog.
     *
     * @param title   the title
     * @param header  the header
     * @param content the content
     */
    public static void showWarningDialog(String title, String header, String content) {
        Platform.runLater(() -> {
            Alert alert = createAlert(Alert.AlertType.WARNING, title, header, content);
            setAlertIcon(alert);
            alert.showAndWait();
        });
    }

    /**
     * Show error dialog.
     *
     * @param title   the title
     * @param header  the header
     * @param content the content
     */
    public static void showErrorDialog(String title, String header, String content) {
        Platform.runLater(() -> {
            Alert alert = createAlert(Alert.AlertType.ERROR, title, header, content);
            setAlertIcon(alert);
            alert.showAndWait();
        });
    }

    /**
     * 创建支持长文本的对话框
     */
    private static Alert createAlert(Alert.AlertType alertType, String title, String header, String content) {
        Alert alert = new Alert(alertType);
        // -------------------------- 2. 绑定CSS + 添加类型标识 --------------------------
        bindDialogCss(alert, alertType);
        setAlertIcon(alert);

        alert.setTitle(title);
        alert.setHeaderText(header);

        // 如果内容过长，使用 TextArea 来显示
        if (content != null && content.length() > 100) {
            // 创建可滚动的文本区域
            TextArea textArea = new TextArea(content);
            textArea.setEditable(false);
            textArea.setWrapText(true);
            textArea.setMaxWidth(Double.MAX_VALUE);
            textArea.setMaxHeight(Double.MAX_VALUE);

            // -------------------------- 3. 移除内联样式，由CSS控制 --------------------------
            // 原内联样式：textArea.setStyle("-fx-font-family: monospace; -fx-font-size: 12px;");
            // 改为添加样式类，对应CSS中的 .dialog-pane .content .grid-pane .text-area
            textArea.getStyleClass().add("dialog-text-area");

            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);

            GridPane expContent = new GridPane();
            expContent.setMaxWidth(Double.MAX_VALUE);
            // 为Label添加样式类，对应CSS中的 .dialog-pane .content .grid-pane .label
            Label detailLabel = new Label("详细信息:");
            detailLabel.getStyleClass().add("dialog-detail-label");
            expContent.add(detailLabel, 0, 0);
            expContent.add(textArea, 0, 1);

            alert.getDialogPane().setContent(expContent);
            // 设置对话框大小
            alert.getDialogPane().setPrefSize(600, 400);
        } else {
            // 短文本直接显示
            alert.setContentText(content);
        }

        return alert;
    }

    /**
     * 显示带详细信息的错误对话框
     */
    public static void showDetailedErrorDialog(String title, String summary, String details) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            // -------------------------- 2. 绑定CSS + 添加类型标识 --------------------------
            bindDialogCss(alert, Alert.AlertType.ERROR);
            setAlertIcon(alert);

            alert.setTitle(title);
            alert.setHeaderText(summary);

            // 创建可滚动的详细文本区域
            TextArea textArea = new TextArea(details);
            textArea.setEditable(false);
            textArea.setWrapText(true);
            textArea.setMaxWidth(Double.MAX_VALUE);
            textArea.setMaxHeight(Double.MAX_VALUE);

            // -------------------------- 3. 移除内联样式，由CSS控制 --------------------------
            textArea.getStyleClass().add("dialog-text-area");

            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);

            GridPane expContent = new GridPane();
            expContent.setMaxWidth(Double.MAX_VALUE);
            Label errorLabel = new Label("错误详情:");
            errorLabel.getStyleClass().add("dialog-detail-label");
            expContent.add(errorLabel, 0, 0);
            expContent.add(textArea, 0, 1);

            alert.getDialogPane().setContent(expContent);
            alert.getDialogPane().setPrefSize(700, 500);
            alert.showAndWait();
        });
    }

    /**
     * 显示带详细信息的警告对话框
     */
    public static void showDetailedWarningDialog(String title, String summary, String details) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            // -------------------------- 2. 绑定CSS + 添加类型标识 --------------------------
            bindDialogCss(alert, Alert.AlertType.WARNING);
            setAlertIcon(alert);

            alert.setTitle(title);
            alert.setHeaderText(summary);

            TextArea textArea = new TextArea(details);
            textArea.setEditable(false);
            textArea.setWrapText(true);
            textArea.setMaxWidth(Double.MAX_VALUE);
            textArea.setMaxHeight(Double.MAX_VALUE);

            // -------------------------- 3. 移除内联样式，由CSS控制 --------------------------
            textArea.getStyleClass().add("dialog-text-area");

            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);

            GridPane expContent = new GridPane();
            expContent.setMaxWidth(Double.MAX_VALUE);
            Label warningLabel = new Label("警告详情:");
            warningLabel.getStyleClass().add("dialog-detail-label");
            expContent.add(warningLabel, 0, 0);
            expContent.add(textArea, 0, 1);

            alert.getDialogPane().setContent(expContent);
            alert.getDialogPane().setPrefSize(700, 500);
            alert.showAndWait();
        });
    }

    /**
     * 显示带详细信息的信息对话框
     */
    public static void showDetailedInformationDialog(String title, String summary, String details) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            // -------------------------- 2. 绑定CSS + 添加类型标识 --------------------------
            bindDialogCss(alert, Alert.AlertType.INFORMATION);
            setAlertIcon(alert);

            alert.setTitle(title);
            alert.setHeaderText(summary);

            TextArea textArea = new TextArea(details);
            textArea.setEditable(false);
            textArea.setWrapText(true);
            textArea.setMaxWidth(Double.MAX_VALUE);
            textArea.setMaxHeight(Double.MAX_VALUE);

            // -------------------------- 3. 移除内联样式，由CSS控制 --------------------------
            textArea.getStyleClass().add("dialog-text-area");

            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);

            GridPane expContent = new GridPane();
            expContent.setMaxWidth(Double.MAX_VALUE);
            Label infoLabel = new Label("详细信息:");
            infoLabel.getStyleClass().add("dialog-detail-label");
            expContent.add(infoLabel, 0, 0);
            expContent.add(textArea, 0, 1);

            alert.getDialogPane().setContent(expContent);
            alert.getDialogPane().setPrefSize(700, 500);
            alert.showAndWait();
        });
    }

    public static void showErrorDialog(String title, String content) {
        showErrorDialog(title, title, content);
    }

    public static void showWarningDialog(String title, String content) {
        showWarningDialog(title, title, content);
    }

    public static void showInformationDialog(String title, String content) {
        showInformationDialog(title, title, content);
    }

    /**
     * 为对话框绑定CSS，并根据类型添加样式类（用于CSS差异化渲染）
     * @param alert 对话框实例
     * @param alertType 对话框类型（ERROR/WARNING/INFORMATION/CONFIRMATION）
     */
    private static void bindDialogCss(Alert alert, Alert.AlertType alertType) {
        DialogPane dialogPane = alert.getDialogPane();
        // 添加dialog-util.css样式
        dialogPane.getStylesheets().add(DIALOG_CSS_PATH);
        // 根据对话框类型添加样式类（对应CSS中的 .dialog-pane:error/.dialog-pane:warning 等）
        switch (alertType) {
            case ERROR:
                dialogPane.getStyleClass().add("error");
                break;
            case WARNING:
                dialogPane.getStyleClass().add("warning");
                break;
            case INFORMATION:
                dialogPane.getStyleClass().add("information");
                break;
            case CONFIRMATION:
                dialogPane.getStyleClass().add("confirmation");
                break;
            default:
                break;
        }
        // 为对话框面板添加基础样式类（确保CSS选择器能匹配）
        dialogPane.getStyleClass().add("dialog-pane");
    }
    // 封装设置Alert图标方法
    private static void setAlertIcon(@NotNull Alert alert) {
        Platform.runLater(() -> {
            Stage alertStage = (Stage) alert.getDialogPane().getScene().getWindow();
            if (alertStage != null) {
                alertStage.getIcons().add(DIALOG_ICON);
            }
        });
    }
}