package top.r3944realms.docchecktoolrefactored.ui.module;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import top.r3944realms.docchecktoolrefactored.System;
import top.r3944realms.docchecktoolrefactored.ui.SceneManager;
import top.r3944realms.docchecktoolrefactored.ui.task.DuplicateDocumentDetectionTask;
import top.r3944realms.docchecktoolrefactored.ui.utils.DialogUtil;
import top.r3944realms.docchecktoolrefactored.ui.utils.ProgressBar;
import top.r3944realms.docchecktoolrefactored.util.LoggerMarker;

import java.io.File;
/**
 * The type Duplicate document pane controller.
 */
@Slf4j
public class DuplicateDocumentPaneController {

    @FXML private TextArea result1TA;
    @FXML private TextField loadFolder1TF;
    @FXML private Button selectLoadFolder1B;
    @FXML private Button start1B;
    @FXML private Button cancel1B;
    private final ProgressBar progressBar = new ProgressBar();
    private DuplicateDocumentDetectionTask currentTask; // 保存任务引用

    /**
     * On select folder.
     *
     * @param actionEvent the action event
     */
    @FXML void onSelectFolder(ActionEvent actionEvent) {
        DirectoryChooser directoryChooser = System.getDirectoryChooser();
        directoryChooser.setTitle("选择要检查的文件夹");
        File selectedFolder = directoryChooser.showDialog(new Stage());
        if (selectedFolder != null) {
            loadFolder1TF.setText(selectedFolder.getAbsolutePath());
            System.setLastModifiedFile(selectedFolder);
        }
    }

    /**
     * On start.
     *
     * @param actionEvent the action event
     */
    @FXML void onStart(ActionEvent actionEvent) {
        // 禁用开始按钮避免重复点击
        start1B.setDisable(true);
        removeResultStyle();
        log.info(LoggerMarker.DEBUG_MARKER, "用户点击了开始查重按钮");
        String folderPath = loadFolder1TF.getText();
        if (folderPath == null || folderPath.trim().isEmpty()) {
            log.warn(LoggerMarker.DEBUG_MARKER, "未选择文件夹，无法进行查重");
            result1TA.setText("请选择要检查的文件夹。");
            DialogUtil.showWarningDialog("警告", "操作有误", "请选择要检查的文件夹");
            start1B.setDisable(false);
            return;
        }
        // 调用提取的样式方法：移除结果文本域错误态
        removeResultStyle();
        // 调用提取的样式方法：添加开始按钮加载态
        addStartButtonLoadingStyle();
        cancel1B.setDisable(false);
        // 显示进度条窗口
        progressBar.showProgress(SceneManager.getPrimaryStage(), "重复文件检测", "正在初始化扫描...");

        // 创建后台任务
        DuplicateDocumentDetectionTask task = new DuplicateDocumentDetectionTask(folderPath);
        // 保存到字段
        currentTask = task;
        // 绑定任务属性到UI
        ChangeListener<Number> progressChangeListener = (obs, oldVal, newVal) -> {
            if (newVal != null) {
                if (task.getMessage() != null) {
                    progressBar.updateProgress(newVal.doubleValue(), task.getMessage());
                }
            }
        };
        task.progressProperty().addListener(progressChangeListener);

        // 绑定任务的消息到结果文本区域
//        ChangeListener<String> messageChangeListener = (observable, oldValue, newValue) -> {
//            result1TA.setText(newValue);
//        };
//        task.messageProperty().addListener(messageChangeListener);

        // 绑定取消按钮 -> task.cancel()
        progressBar.setOnCancel(() -> {
            if (currentTask != null && currentTask.isRunning()) {
                cancel1B.setDisable(false);
                currentTask.cancel();
            }
        });

        // 当任务完成时显示完整结果
        task.setOnSucceeded(e -> {
            progressBar.closeProgress();
            result1TA.setText(task.getValue());
            start1B.setDisable(false);
            cancel1B.setDisable(true);
            // 调用提取的样式方法：移除开始按钮加载态
            removeStartButtonLoadingStyle();
            addResultSuccessfulStyle();
            log.info(LoggerMarker.RELEASE_MARKER, "查重任务完成，结果如下：{}", task.getValue());
        });

        // 处理任务失败情况
        task.setOnFailed(e -> {
            progressBar.closeProgress();
            Throwable exception = task.getException();
            currentTask.progressProperty().removeListener(progressChangeListener);
//            currentTask.messageProperty().removeListener(messageChangeListener);
            result1TA.setText("检测过程中发生错误: " + exception.getMessage());
            // 调用提取的样式方法：添加结果文本域错误态
            addResultErrorStyle();
            DialogUtil.showDetailedErrorDialog("错误", "检测过程中发生错误", exception.getMessage());
            start1B.setDisable(false);
            // 调用提取的样式方法：移除开始按钮加载态
            removeStartButtonLoadingStyle();
            cancel1B.setDisable(true);
            log.error(LoggerMarker.RELEASE_MARKER, "查重任务失败", exception);
        });

        // 处理任务取消情况
        task.setOnCancelled(e -> {
            progressBar.closeProgress();
            currentTask.progressProperty().removeListener(progressChangeListener);
//            currentTask.messageProperty().removeListener(messageChangeListener);
            result1TA.appendText("\n检测已取消");
            start1B.setDisable(false);
            // 调用提取的样式方法：移除开始按钮加载态
            removeStartButtonLoadingStyle();
            cancel1B.setDisable(true);
            log.info(LoggerMarker.RELEASE_MARKER, "查重任务已被取消");
        });
        // 在新线程中执行任务
        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();
    }

    public void onCancel(ActionEvent actionEvent) {
        if (currentTask != null && currentTask.isRunning()) {
            currentTask.cancel(); // 触发 setOnCancelled
        } else {
            log.warn(LoggerMarker.DEBUG_MARKER, "没有正在运行的任务可取消");
        }
    }

    // ======================== 提取的样式变更方法 ========================
    /**
     * 为结果文本域添加错误态样式
     */
    private void addResultErrorStyle() {
        Platform.runLater(() -> {
            result1TA.getStyleClass().add("result-error");
        });
    }
    /**
     * 为结果文本域添加成功态样式
     */
    private void addResultSuccessfulStyle() {
        Platform.runLater(() -> {
            result1TA.getStyleClass().add("result-error");
        });
    }

    /**
     * 为结果文本域移除样式
     */
    private void removeResultStyle() {
        Platform.runLater(() -> {
            result1TA.getStyleClass().remove("result-error");
            result1TA.getStyleClass().remove("result-success");
        });
    }

    /**
     * 为开始按钮添加加载态样式
     */
    private void addStartButtonLoadingStyle() {
        Platform.runLater(() -> {
            start1B.getStyleClass().add("loading");
        });
    }

    /**
     * 为开始按钮移除加载态样式
     */
    private void removeStartButtonLoadingStyle() {
        Platform.runLater(() -> {
            start1B.getStyleClass().remove("loading");
        });
    }
    // ====================================================================
}