package dev.bytevibe.hyperpoint;

import dev.bytevibe.hyperpoint.Utils.MyAlert;
import dev.bytevibe.hyperpoint.Utils.MyTextInputDialog;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

public class Controller implements Initializable {
    @FXML
    private ListView<SlidePage> pageListView;
    @FXML
    private Label pageNameLabel;
    @FXML
    private AnchorPane drawingCanvasContainer;
    @FXML
    private VBox propertyPanelContainer;
    @FXML
    private AnchorPane scenePane;

    private Slide currentSlide;
    private DrawingCanvas drawingCanvas;
    private PropertyPanel propertyPanelComponent;
    Stage stage;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        pageListView.setDisable(true);

        // 添加页面列表选择监听
        pageListView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal != null) {
                displayPageContent(newVal);
            }
        });
    }

    /**
     * 新建幻灯片按钮的事件处理
     */
    @FXML
    public void onNewSlide(ActionEvent actionEvent) {
        MyTextInputDialog dialog = new MyTextInputDialog("我的幻灯片");
        dialog.setTitle("创建幻灯片");
        dialog.setHeaderText("请输入幻灯片名称");
        dialog.setContentText("幻灯片名称:");

        if (dialog.showAndWait().isPresent()) {
            String slideName = dialog.getResult();
            if (!slideName.trim().isEmpty()) {
                currentSlide = new Slide(slideName);
                loadSlidePages();

                MyAlert alert = new MyAlert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText("幻灯片已创建");
                alert.setContentText("幻灯片 \"" + slideName + "\" 已创建。");
                stage = (Stage) scenePane.getScene().getWindow();
                if (stage != null) {
                    stage.setTitle("Hyperpoint - " + slideName);
                }
                alert.showAndWait();
            } else {
                showWarning("无效名称", "幻灯片名称不能为空。");
            }
        }
    }

    /**
     * 加载幻灯片的所有页面到列表中
     */
    private void loadSlidePages() {
        if (currentSlide != null) {
            pageListView.setItems(currentSlide.getPages());
            pageListView.setDisable(false);

            if (!currentSlide.getPages().isEmpty()) {
                pageListView.getSelectionModel().selectFirst();
            }
        }
    }

    /**
     * 显示页面内容
     */
    private void displayPageContent(SlidePage page) {
        if (page != null) {
            pageNameLabel.setText("页面名称: " + page.getTitle());

            // 移除旧的Canvas
            drawingCanvasContainer.getChildren().clear();
            propertyPanelContainer.getChildren().clear();

            // 创建新的Canvas
            PageContent pageContent = page.getPageContent();
            drawingCanvas = new DrawingCanvas(pageContent);
            drawingCanvasContainer.getChildren().add(drawingCanvas);

            // 使用AnchorPane的约束来填充容器
            AnchorPane.setTopAnchor(drawingCanvas, 0.0);
            AnchorPane.setLeftAnchor(drawingCanvas, 0.0);
            AnchorPane.setRightAnchor(drawingCanvas, 0.0);
            AnchorPane.setBottomAnchor(drawingCanvas, 0.0);

            // 创建属性面板
            propertyPanelComponent = new PropertyPanel(drawingCanvas);
            propertyPanelContainer.getChildren().add(propertyPanelComponent);
        }
    }

    /**
     * 新建页面按钮的事件处理
     */
    @FXML
    public void onNewPage(ActionEvent actionEvent) {
        if (currentSlide == null) {
            showWarning("无幻灯片", "请先打开或创建一个幻灯片。");
            return;
        }

        MyTextInputDialog dialog = new MyTextInputDialog("页面 " + (currentSlide.getPages().size() + 1));
        dialog.setTitle("新建页面");
        dialog.setHeaderText("请输入页面名称");
        dialog.setContentText("页面名称:");

        if (dialog.showAndWait().isPresent()) {
            String pageName = dialog.getResult();
            if (!pageName.trim().isEmpty()) {
                SlidePage newPage = new SlidePage(pageName);
                currentSlide.addPage(newPage);

                pageListView.refresh();
                pageListView.getSelectionModel().selectLast();

                MyAlert alert = new MyAlert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText("页面已创建");
                alert.setContentText("新页面 \"" + pageName + "\" 已添加。");
                alert.showAndWait();
            }
        }
    }

    /**
     * 删除页面按钮的事件处理
     */
    @FXML
    public void onDeletePage(ActionEvent actionEvent) {
        if (currentSlide == null || currentSlide.getPages().isEmpty()) {
            showWarning("无法删除", "没有可删除的页面。");
            return;
        }

        int selectedIndex = pageListView.getSelectionModel().getSelectedIndex();
        if (selectedIndex < 0) {
            showWarning("请选择页面", "请先选择要删除的页面。");
            return;
        }

        Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
        confirmAlert.setTitle("确认删除");
        confirmAlert.setHeaderText("确认删除该页面？");
        confirmAlert.setContentText("删除后无法恢复，确定继续吗？");

        var result = confirmAlert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            if (currentSlide.removePage(selectedIndex)) {
                pageListView.refresh();

                if (selectedIndex >= currentSlide.getPages().size()) {
                    pageListView.getSelectionModel().selectLast();
                } else {
                    pageListView.getSelectionModel().select(selectedIndex);
                }

                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText("页面已删除");
                alert.showAndWait();
            } else {
                showWarning("无法删除", "幻灯片至少需要保留一个页面。");
            }
        }
    }

    /**
     * 添加文本按钮的事件处理
     */
    @FXML
    public void onAddText(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }

        TextInputDialog dialog = new TextInputDialog("输入文本");
        dialog.setTitle("添加文本");
        dialog.setHeaderText("请输入要添加的文本");
        dialog.setContentText("文本内容:");

        if (dialog.showAndWait().isPresent()) {
            String text = dialog.getResult();
            if (!text.trim().isEmpty()) {
                TextObject textObj = new TextObject(50, 50, text);
                drawingCanvas.addObject(textObj);
            }
        }
    }

    /**
     * 添加直线按钮的事件处理
     */
    @FXML
    public void onAddLine(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }
        ShapeObject line = new ShapeObject(50, 50, 100, 100, ShapeObject.ShapeType.LINE);
        drawingCanvas.addObject(line);
    }

    /**
     * 添加矩形按钮的事件处理
     */
    @FXML
    public void onAddRectangle(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }
        ShapeObject rect = new ShapeObject(50, 50, 100, 60, ShapeObject.ShapeType.RECTANGLE);
        drawingCanvas.addObject(rect);
    }

    /**
     * 添加圆形按钮的事件处理
     */
    @FXML
    public void onAddCircle(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }
        ShapeObject circle = new ShapeObject(50, 50, 100, 100, ShapeObject.ShapeType.CIRCLE);
        drawingCanvas.addObject(circle);
    }

    /**
     * 添加椭圆按钮的事件处理
     */
    @FXML
    public void onAddEllipse(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }
        ShapeObject ellipse = new ShapeObject(50, 50, 150, 80, ShapeObject.ShapeType.ELLIPSE);
        drawingCanvas.addObject(ellipse);
    }

    /**
     * 添加图片按钮的事件处理
     */
    @FXML
    public void onAddImage(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        stage = (Stage) scenePane.getScene().getWindow();
        File file = fileChooser.showOpenDialog(stage);

        if (file != null) {
            ImageObject imgObj = new ImageObject(50, 50, 200, 150, file.getAbsolutePath());
            drawingCanvas.addObject(imgObj);
        }
    }

    /**
     * 退出按钮的事件处理
     */
    @FXML
    public void logout(ActionEvent actionEvent) {
        MyAlert alert = new MyAlert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("退出");
        alert.setHeaderText("您确定要退出吗？");
        alert.setContentText("点击确定退出，点击取消返回。");

        if (alert.showAndWait().orElse(null) == MyAlert.isOK()) {
            stage = (Stage) scenePane.getScene().getWindow();
            stage.close();
        }
    }

    /**
     * 打开幻灯片文件
     */
    @FXML
    public void onOpenSlideFile(ActionEvent actionEvent) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("打开幻灯片");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("幻灯片文件 (*.hyperpoint)", "*.hyperpoint"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        stage = (Stage) scenePane.getScene().getWindow();
        File file = fileChooser.showOpenDialog(stage);

        if (file != null) {
            try {
                Presentation presentation = JsonSerializationUtil.loadFromJson(file);
                currentSlide = presentation.getSlides().isEmpty() ? null : presentation.getSlides().get(0);

                if (currentSlide != null) {
                    loadSlidePages();
                    stage.setTitle("Hyperpoint - " + presentation.getName());

                    MyAlert alert = new MyAlert(Alert.AlertType.INFORMATION);
                    alert.setTitle("成功");
                    alert.setHeaderText("幻灯片已打开");
                    alert.setContentText("幻灯片 \"" + presentation.getName() + "\" 已成功加载，包含 " + currentSlide.getPages().size() + " 个页面。");
                    alert.showAndWait();
                } else {
                    showWarning("加载失败", "幻灯片中没有找到任何页面。");
                }
            } catch (Exception e) {
                showWarning("错误", "无法加载幻灯片文件: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存幻灯片文件
     */
    @FXML
    public void onSaveSlide(ActionEvent actionEvent) {
        if (currentSlide == null) {
            showWarning("无幻灯片", "请先创建或打开一个幻灯片。");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("保存幻灯片");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("幻灯片文件", "*.hyperpoint"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        fileChooser.setInitialFileName(currentSlide.getName() + ".hyperpoint");

        stage = (Stage) scenePane.getScene().getWindow();
        File file = fileChooser.showSaveDialog(stage);

        if (file != null) {
            try {
                // 创建临时演示文稿对象用于保存
                Presentation tempPresentation = new Presentation(currentSlide.getName());
                tempPresentation.addSlide(currentSlide);

                JsonSerializationUtil.saveToJson(tempPresentation, file);

                MyAlert alert = new MyAlert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText("幻灯片已保存");
                alert.setContentText("幻灯片已保存到: " + file.getAbsolutePath());
                alert.showAndWait();
            } catch (Exception e) {
                showWarning("错误", "无法保存幻灯片文件: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出页面为图片
     */
    @FXML
    public void onExportPage(ActionEvent actionEvent) {
        if (drawingCanvas == null) {
            showWarning("请先选择页面", "请先选择一个页面。");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出页面为图片");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("PNG图片 (*.png)", "*.png"),
                new FileChooser.ExtensionFilter("JPG图片 (*.jpg)", "*.jpg"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        SlidePage currentPage = pageListView.getSelectionModel().getSelectedItem();
        if (currentPage != null) {
            fileChooser.setInitialFileName(currentPage.getTitle() + ".png");
        }

        stage = (Stage) scenePane.getScene().getWindow();
        File file = fileChooser.showSaveDialog(stage);

        if (file != null) {
            try {
                String format = file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg") ? "jpg" : "png";
                ExportUtil.exportPageAsImage(drawingCanvas, file, format);

                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText("页面已导出");
                alert.setContentText("页面已导出到: " + file.getAbsolutePath());
                alert.showAndWait();
            } catch (Exception e) {
                showWarning("错误", "无法导出页面: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出幻灯片为PDF
     */
    @FXML
    public void onExportSlide(ActionEvent actionEvent) {
        if (currentSlide == null) {
            showWarning("无幻灯片", "请先创建或打开一个幻灯片。");
            return;
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出幻灯片为PDF");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("PDF文件 (*.pdf)", "*.pdf"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );
        fileChooser.setInitialFileName(currentSlide.getName() + ".pdf");

        stage = (Stage) scenePane.getScene().getWindow();
        File file = fileChooser.showSaveDialog(stage);

        if (file != null) {
            try {
                ExportUtil.exportSlideToPDF(currentSlide, file);

                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("成功");
                alert.setHeaderText("幻灯片已导出为PDF");
                alert.setContentText("PDF已导出到: " + file.getAbsolutePath());
                alert.showAndWait();
            } catch (Exception e) {
                showWarning("错误", "无法导出PDF: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 显示警告对话框
     */
    private void showWarning(String title, String message) {
        MyAlert alert = new MyAlert(Alert.AlertType.WARNING);
        alert.setTitle(title);
        alert.setHeaderText(title);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
