package top.r3944realms.docchecktoolrefactored.ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.docchecktoolrefactored.System;
import top.r3944realms.docchecktoolrefactored.core.Setting;
import top.r3944realms.docchecktoolrefactored.ui.utils.DialogUtil;
import top.r3944realms.docchecktoolrefactored.util.LoggerMarker;


import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;



/**
 * The type Main stage controller.
 */
@Slf4j
public class MainStageController {

    @FXML public Button nextB;
    @FXML public Button prevB;
    @FXML private Tab step1T;
    @FXML private Tab step2T;
    @FXML private Tab step3T;
    @FXML private Tab step4T;
    @FXML private Tab step5T;
    @FXML private Tab step6T;
    @FXML private Tab step7T;
    @FXML private TabPane tabPane;
    @FXML private Menu helpM;
    @FXML private MenuItem aboutSoftwareMI;
    @FXML private MenuItem helpDocMI;
    @FXML private MenuItem exitMI;
    @FXML private MenuItem logoutMI;
    @FXML private MenuItem settingMI;

    private List<Tab> tabs;
    private int currentIndex = 0;

    @FXML
    public void initialize() {
        // 初始化所有Tab的集合
        tabs = new ArrayList<>();
        tabs.add(step1T);
        tabs.add(step2T);
        tabs.add(step3T);
        tabs.add(step4T);
        tabs.add(step5T);
        tabs.add(step6T);
        tabs.add(step7T);

        // 初始状态设置
        updateButtonStates();
        updateStepButtonsVisibility(); // 根据配置初始可见性
        // 监听Tab切换事件
        tabPane.getSelectionModel().selectedItemProperty().addListener((obs, oldTab, newTab) -> {
            currentIndex = tabs.indexOf(newTab);
            updateButtonStates();
        });
    }

    /**
     * 更新按钮状态
     */
    private void updateButtonStates() {
        prevB.setDisable(currentIndex == 0);
        nextB.setDisable(currentIndex == tabs.size() - 1);
    }

    /**
     * 切换到下一个Tab
     * @param actionEvent 事件
     */
    @FXML
    void onNext(ActionEvent actionEvent) {
        if (currentIndex < tabs.size() - 1) {
            tabPane.getSelectionModel().select(tabs.get(currentIndex + 1));
        }
    }

    /**
     * 切换到上一个Tab
     * @param actionEvent 事件
     */
    @FXML
    void onPrev(ActionEvent actionEvent) {
        if (currentIndex > 0) {
            tabPane.getSelectionModel().select(tabs.get(currentIndex - 1));
        }
    }

    /**
     * 处理键盘快捷键
     * @param keyEvent 键盘事件
     */
    @FXML
    void handleKeyPressed(KeyEvent keyEvent) {
        // Ctrl+> 或 Ctrl+. 切换到下一个Tab
        if (new KeyCodeCombination(KeyCode.PERIOD, KeyCombination.CONTROL_DOWN).match(keyEvent) ||
                new KeyCodeCombination(KeyCode.GREATER, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
            onNext(null);
            keyEvent.consume();
        }
        // Ctrl+< 或 Ctrl+, 切换到上一个Tab
        else if (new KeyCodeCombination(KeyCode.COMMA, KeyCombination.CONTROL_DOWN).match(keyEvent) ||
                new KeyCodeCombination(KeyCode.LESS, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
            onPrev(null);
            keyEvent.consume();
        }
    }

    @FXML void onLogout(ActionEvent actionEvent) {
        SceneManager.switchLoginView();
    }

    @FXML void onExit(ActionEvent actionEvent) {
        // 显示退出确认对话框
        boolean confirmExit = DialogUtil.showExitConfirmation(tabPane.getScene().getWindow());

        if (confirmExit) {
            // 执行退出操作
            exitApplication();
        }
    }
    /**
     * 退出应用程序
     */
    private void exitApplication() {
        try {
            // 保存当前设置（如果需要）
            System.saveSettingsNow();
            log.info(LoggerMarker.DEBUG_MARKER, "应用程序正常退出");

            // 关闭应用程序
            SceneManager.getPrimaryStage().close();

            // 强制退出JVM（确保所有线程都终止）
            java.lang.System.exit(0);

        } catch (Exception e) {
            // 退出过程中发生错误，仍然强制退出
            log.error(LoggerMarker.DEBUG_MARKER, "退出应用程序时发生错误", e);
            java.lang.System.exit(1); // 非正常退出
        }
    }

    @FXML void onOpenSetting(ActionEvent actionEvent) {
        SceneManager.openSettingView();
    }


    @FXML
    void onOpenHelpDoc(ActionEvent actionEvent) {
        try {
            // 获取帮助文档文件路径（如果不存在则从资源中释放）
            File helpFile = getOrExtractHelpDocument();

            if (helpFile.exists()) {
                // 打开文档
                openDocument(helpFile);
            } else {
                DialogUtil.showErrorDialog("打开失败", "帮助文档不存在",
                        "无法找到帮助文档，请联系技术支持。");
            }
        } catch (Exception e) {
            DialogUtil.showDetailedErrorDialog("打开失败", "无法打开帮助文档",
                    "错误信息：" + e.getMessage());
        }
    }

    /**
     * 获取或从资源中提取帮助文档
     */
    private File getOrExtractHelpDocument() throws IOException {
        // 获取程序运行目录
        String appDir = java.lang.System.getProperty("user.dir");
        File helpFile = new File(appDir, HELP_DOC_FILE_NAME);

        // 如果文件不存在，则从资源中复制出来
        if (!helpFile.exists()) {
            try (InputStream resourceStream = getClass().getResourceAsStream(HELP_DOC_RESOURCE_PATH)) {
                if (resourceStream == null) {
                    throw new FileNotFoundException("资源中未找到帮助文档: " + HELP_DOC_RESOURCE_PATH);
                }

                // 复制资源到程序目录
                Files.copy(resourceStream, helpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }

        return helpFile;
    }

    // 帮助文档在资源中的路径
    private static final String HELP_DOC_RESOURCE_PATH = "/docs/UserHelpDocument.docx";
    // 释放到外部的文件名
    private static final String HELP_DOC_FILE_NAME = "操作手册.docx";

    /**
     * 使用系统默认程序打开文档
     */
    private void openDocument(File file) throws IOException {
        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.OPEN)) {
                desktop.open(file);
            } else {
                throw new UnsupportedOperationException("系统不支持打开文件操作");
            }
        } else {
            // 对于不支持Desktop的环境（如某些Linux系统）
            String os = java.lang.System.getProperty("os.name").toLowerCase();
            ProcessBuilder pb = getProcessBuilder(file, os);

            pb.start();
        }
    }

    private static @NotNull ProcessBuilder getProcessBuilder(File file, String os) {
        ProcessBuilder pb;

        if (os.contains("win")) {
            pb = new ProcessBuilder("cmd.exe", "/c", file.getAbsolutePath());
        } else if (os.contains("mac")) {
            pb = new ProcessBuilder("open", file.getAbsolutePath());
        } else if (os.contains("nix") || os.contains("nux")) {
            pb = new ProcessBuilder("xdg-open", file.getAbsolutePath());
        } else {
            throw new UnsupportedOperationException("不支持的操作系统");
        }
        return pb;
    }


    @FXML void onAbout(ActionEvent actionEvent) {
        DialogUtil.showDetailedInformationDialog("关于软件", "数字化验收工具","软件版本：" + System.version() + "\n");
    }
    public void updateStepButtonsVisibility() {
        Setting setting = System.getSetting();
        boolean visible = setting.isEnableStep(); // 由enableStep控制
        nextB.setVisible(visible);
        prevB.setVisible(visible);
    }
}