package client;

import Server.Automaton.Game;
import Server.Player;
import Server.TotemColor;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class DeckViewerFX extends Application {

    private PDDocument document;
    private PDFRenderer pdfRenderer;
    private int currentIndex = 0;
    private int totalCards = 0;

    private ImageView cardImageView;
    private Label pageLabel;
    private Button btnPrev;
    private Button btnNext;

    @Override
    public void start(Stage primaryStage) {

        List<Player> players = new ArrayList<>();
        players.add(new Player("Yoshi", TotemColor.YELLOW));
        players.add(new Player("Pippo", TotemColor.PURPLE));
        players.add(new Player("John", TotemColor.RED));
        players.add(new Player("Baggio", TotemColor.BLUE));
        players.add(new Player("Gino", TotemColor.GREEN));

        Game game = new Game(players);
        InputStream csvStream = getClass().getResourceAsStream("/files/cards.csv");
        game.newGame(csvStream);

        primaryStage.setTitle("Visualizzatore Mazzo di Carte (PDF)");

        // Componente per mostrare la carta
        cardImageView = new ImageView();
        cardImageView.setFitHeight(500); // Altezza fissa, larghezza in proporzione
        cardImageView.setPreserveRatio(true);
        cardImageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.5), 10, 0, 0, 0);");

        // Controlli UI
        btnPrev = new Button("⬅ Carta Precedente");
        btnNext = new Button("Carta Successiva ➡");
        pageLabel = new Label("Nessun mazzo caricato");
        Button btnLoad = new Button("Carica PDF Mazzo");

        // Azioni dei pulsanti
        btnLoad.setOnAction(e -> loadPdf(primaryStage));
        btnPrev.setOnAction(e -> showCard(currentIndex - 1));
        btnNext.setOnAction(e -> showCard(currentIndex + 1));

        updateButtons();

        // Layout
        HBox controls = new HBox(15, btnPrev, pageLabel, btnNext);
        controls.setAlignment(Pos.CENTER);

        VBox topBox = new VBox(10, btnLoad);
        topBox.setAlignment(Pos.CENTER);
        topBox.setPadding(new Insets(10));

        BorderPane root = new BorderPane();
        root.setTop(topBox);
        root.setCenter(cardImageView);
        root.setBottom(controls);
        BorderPane.setMargin(cardImageView, new Insets(20));
        BorderPane.setMargin(controls, new Insets(20));

        Scene scene = new Scene(root, 600, 700);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void loadPdf(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Seleziona il PDF del mazzo di carte");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("File PDF", "*.pdf"));
        File file = fileChooser.showOpenDialog(stage);

        if (file != null) {
            try {
                // Chiude il documento precedente se esiste
                if (document != null) {
                    document.close();
                }

                // Carica il nuovo PDF
                document = PDDocument.load(file);
                pdfRenderer = new PDFRenderer(document);
                totalCards = document.getNumberOfPages();

                // Mostra la prima carta
                showCard(0);
            } catch (IOException e) {
                e.printStackTrace();
                pageLabel.setText("Errore nel caricamento del file!");
            }
        }
    }

    private void showCard(int index) {
        if (document == null || index < 0 || index >= totalCards) return;

        try {
            // Renderizza la pagina del PDF in un'immagine BufferedImage (DPI 150 per buona qualità)
            BufferedImage bim = pdfRenderer.renderImageWithDPI(index, 150);

            // Converte l'immagine di AWT (Swing) in un'immagine JavaFX
            Image fxImage = SwingFXUtils.toFXImage(bim, null);

            cardImageView.setImage(fxImage);
            currentIndex = index;
            pageLabel.setText("Carta " + (currentIndex + 1) + " di " + totalCards);

            updateButtons();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateButtons() {
        btnPrev.setDisable(document == null || currentIndex == 0);
        btnNext.setDisable(document == null || currentIndex == totalCards - 1);
    }

    @Override
    public void stop() throws Exception {
        // Importante: chiudere il documento per liberare la memoria quando l'app si chiude
        if (document != null) {
            document.close();
        }
        super.stop();
    }

    public static void main(String[] args) {
        launch(args);
    }
}