package org.example.mesosll07;

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.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.util.*;
import java.util.stream.Collectors;

public class DeckGridApp2 extends Application {

    private static final Logger logger = LogManager.getLogger(DeckGridApp2.class);

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

    // Contenitori Layout
    private HBox topRow;
    private HBox centerRow;
    private HBox bottomRow;
    private HBox playersArea; // NUOVO: Area per i giocatori
    private Button btnShuffle;

    // --- LOGICA DI GIOCO SIMULATA ---
    public enum CardType {
        CACCIA, UTENSILI, RITUALI, COSTRUZIONI
    }

    public static class Card {
        int pdfPageIndex;
        CardType type;

        public Card(int pdfPageIndex, CardType type) {
            this.pdfPageIndex = pdfPageIndex;
            this.type = type;
        }
        public CardType getType() { return type; }
    }

    public static class Player {
        String name;
        int food;
        int money;
        List<Card> hand = new ArrayList<>();

        public Player(String name, int food, int money) {
            this.name = name;
            this.food = food;
            this.money = money;
        }
        public List<Card> getHand() { return hand; }
    }
    // --------------------------------

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Tavolo da Gioco - Board & Players");

        Button btnLoad = new Button("Carica PDF Mazzo");
        btnShuffle = new Button("Rimescola & Distribuisci");
        btnShuffle.setDisable(true);

        btnLoad.setOnAction(e -> loadPdf(primaryStage));
        btnShuffle.setOnAction(e -> distributeAll());

        HBox topMenu = new HBox(15, btnLoad, btnShuffle);
        topMenu.setAlignment(Pos.CENTER);
        topMenu.setPadding(new Insets(10));

        topRow = createRowContainer();
        centerRow = createRowContainer();
        bottomRow = createRowContainer();

        // NUOVO: Inizializza l'area giocatori
        playersArea = new HBox(30);
        playersArea.setAlignment(Pos.CENTER);
        playersArea.setPadding(new Insets(20));

        VBox tableArea = new VBox(20,
                new Label("TOP (8 Carte):"), topRow,
                new Label("CENTER (6 Carte):"), centerRow,
                new Label("BOTTOM (7 Carte):"), bottomRow,
                new Label("--- SITUAZIONE GIOCATORI ---"), playersArea
        );
        tableArea.setAlignment(Pos.CENTER);
        tableArea.setPadding(new Insets(20));

        ScrollPane scrollPane = new ScrollPane(tableArea);
        scrollPane.setFitToWidth(true);

        BorderPane root = new BorderPane();
        root.setTop(topMenu);
        root.setCenter(scrollPane);

        Scene scene = new Scene(root, 1300, 900);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private HBox createRowContainer() {
        HBox row = new HBox(10);
        row.setAlignment(Pos.CENTER);
        return row;
    }

    private void loadPdf(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("File PDF", "*.pdf"));
        File file = fileChooser.showOpenDialog(stage);

        if (file != null) {
            try {
                if (document != null) document.close();
                document = PDDocument.load(file);
                pdfRenderer = new PDFRenderer(document);
                totalCards = document.getNumberOfPages();
                btnShuffle.setDisable(false);

                distributeAll();
            } catch (IOException e) {
                logger.error("Errore PDF", e);
            }
        }
    }

    private void distributeAll() {
        if (document == null || totalCards == 0) return;

        topRow.getChildren().clear();
        centerRow.getChildren().clear();
        bottomRow.getChildren().clear();
        playersArea.getChildren().clear();

        List<Integer> deck = new ArrayList<>();
        for (int i = 0; i < totalCards; i++) deck.add(i);
        Collections.shuffle(deck);

        // Distribuisce sul tavolo le prime 21 carte
        int index = 0;
        index = populateTable(topRow, deck, index, 8);
        index = populateTable(centerRow, deck, index, 6);
        index = populateTable(bottomRow, deck, index, 7);

        // NUOVO: Simula 2 giocatori con le carte rimanenti
        Random rand = new Random();
        List<Player> players = Arrays.asList(
                new Player("Giocatore 1 (Tribù Rossa)", rand.nextInt(15), rand.nextInt(50)),
                new Player("Giocatore 2 (Tribù Blu)", rand.nextInt(15), rand.nextInt(50))
        );

        // Assegna 5 carte a caso a ogni giocatore e simula il loro Tipo
        CardType[] types = CardType.values();
        for (Player p : players) {
            for (int i = 0; i < 5; i++) {
                if (index < deck.size()) {
                    CardType randomType = types[rand.nextInt(types.length)];
                    p.getHand().add(new Card(deck.get(index), randomType));
                    index++;
                }
            }
        }

        // Renderizza i giocatori nella UI
        renderPlayers(players);
    }

    private int populateTable(HBox row, List<Integer> deck, int startIndex, int amount) {
        for (int i = 0; i < amount; i++) {
            if (startIndex >= deck.size()) break;
            ImageView card = createCardImage(deck.get(startIndex), 150); // Altezza 150px
            if (card != null) row.getChildren().add(card);
            startIndex++;
        }
        return startIndex;
    }

    // --- NUOVO: RENDERIZZAZIONE GIOCATORI E RAGGRUPPAMENTO (JAVA 8) ---
    private void renderPlayers(List<Player> players) {
        for (Player player : players) {
            VBox playerBox = new VBox(10);
            playerBox.setPadding(new Insets(15));
            playerBox.setStyle("-fx-border-color: #555; -fx-border-width: 2; -fx-border-radius: 10; -fx-background-color: #f9f9f9; -fx-background-radius: 10;");

            // Intestazione Giocatore
            Label nameLbl = new Label(player.name);
            nameLbl.setFont(Font.font("System", FontWeight.BOLD, 16));

            // Risorse Cibo e Soldi
            Label statsLbl = new Label("🍖 Cibo: " + player.food + "   |   💰 Money: " + player.money);
            statsLbl.setTextFill(Color.DARKRED);
            statsLbl.setFont(Font.font("System", FontWeight.BOLD, 14));

            playerBox.getChildren().addAll(nameLbl, statsLbl);

            // JAVA 8 MAGIA: Raggruppa le carte del giocatore per Tipo!
            Map<CardType, List<Card>> groupedCards = player.getHand().stream()
                    .collect(Collectors.groupingBy(Card::getType));

            // Itera sui gruppi creati e genera la grafica
            groupedCards.forEach((type, cardsOfType) -> {
                Label typeLbl = new Label("Tipo: " + type.name() + " (" + cardsOfType.size() + ")");
                typeLbl.setFont(Font.font("System", FontWeight.NORMAL, 12));

                HBox cardImagesRow = new HBox(5);
                for (Card c : cardsOfType) {
                    // Carte più piccole (90px) per l'area giocatore
                    ImageView img = createCardImage(c.pdfPageIndex, 90);
                    if (img != null) cardImagesRow.getChildren().add(img);
                }

                playerBox.getChildren().addAll(typeLbl, cardImagesRow);
            });

            playersArea.getChildren().add(playerBox);
        }
    }

    private ImageView createCardImage(int pageIndex, int height) {
        try {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(pageIndex, 100);
            Image fxImage = SwingFXUtils.toFXImage(bim, null);
            ImageView imageView = new ImageView(fxImage);
            imageView.setFitHeight(height);
            imageView.setPreserveRatio(true);
            imageView.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.4), 4, 0, 0, 0);");
            return imageView;
        } catch (IOException e) {
            logger.error("Errore rendering pagina {}", pageIndex, e);
            return null;
        }
    }

    @Override
    public void stop() throws Exception {
        if (document != null) document.close();
        super.stop();
    }

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