package eu.mhsl.minenet.minigames.instance.game.stateless.types.elytraRace;

import eu.mhsl.minenet.minigames.instance.Dimension;
import eu.mhsl.minenet.minigames.instance.game.stateless.StatelessGame;
import eu.mhsl.minenet.minigames.message.Countdown;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
import eu.mhsl.minenet.minigames.message.type.TitleMessage;
import eu.mhsl.minenet.minigames.score.FirstWinsScore;
import eu.mhsl.minenet.minigames.util.*;
import eu.mhsl.minenet.minigames.world.BlockPallet;
import eu.mhsl.minenet.minigames.world.generator.featureEnriched.ValeGenerator;
import eu.mhsl.minenet.minigames.world.generator.terrain.PlaneTerrainGenerator;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.minestom.server.coordinate.Point;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.coordinate.Vec;
import net.minestom.server.entity.EquipmentSlot;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.*;
import net.minestom.server.instance.batch.AbsoluteBlockBatch;
import net.minestom.server.instance.block.Block;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.minestom.server.network.packet.server.play.ParticlePacket;
import net.minestom.server.particle.Particle;
import net.minestom.server.sound.SoundEvent;
import org.jetbrains.annotations.NotNull;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;


public class ElytraRace extends StatelessGame {
    private final ValeGenerator vale = new ValeGenerator();

    private final int gameHeight = 0;
    private final int seaLevel = -55;
    private final int ringSpacing = 100;
    private final int ringCount;

    private final Material boostMaterial = Material.FIREWORK_ROCKET;
    private final Material resetMaterial = Material.RED_DYE;
    private final int boostMultiplier = 50;
    private final Material ringMaterial = Material.GOLD_BLOCK;
    private int generatedUntil = 0;

    private record CheckPointData(int currentCheckpoint, int nextCheckpoint) {
        public CheckPointData next(int spacing) {
            return new CheckPointData(nextCheckpoint, nextCheckpoint + spacing);
        }
    }
    private final Map<Player, CheckPointData> playerCheckpoints = new HashMap<>();

    public ElytraRace(int ringCount) {
        super(Dimension.OVERWORLD.key, "ElytraRace", new FirstWinsScore());

        this.ringCount = ringCount;

        setGenerator(vale);
        vale.setCalculateSeaLevel(point -> seaLevel);
        vale.setXShiftMultiplier(integer -> NumberUtil.map(integer, 50, 500, 0, 1));
        vale.addMixIn(new PlaneTerrainGenerator(gameHeight, Block.BARRIER));

        eventNode().addListener(PlayerUseItemEvent.class, playerUseItemEvent -> {
            Player player = playerUseItemEvent.getPlayer();
            Material usedMaterial = playerUseItemEvent.getItemStack().material();

            if(usedMaterial.equals(boostMaterial)) {
               if(!player.isFlyingWithElytra()) return;

               boost(player);
               InventoryUtil.removeItemFromPlayer(player, boostMaterial, 1);
            } else if(usedMaterial.equals(resetMaterial)) {
                toCheckpoint(player);
                InventoryUtil.removeItemFromPlayer(player, resetMaterial, 1);
            }
        });

        eventNode().addListener(PlayerStopFlyingWithElytraEvent.class, playerStopFlyingWithElytraEvent -> {
            Player player = playerStopFlyingWithElytraEvent.getPlayer();
            if(Position.blocksBelowPlayer(this, player).contains(ringMaterial.block())) {
                player.setFlyingWithElytra(true);
                boost(player);
            } else {
                toCheckpoint(player);
//                getScore().insertResult(playerStopFlyingWithElytraEvent.getPlayer());
//                playerStopFlyingWithElytraEvent.getPlayer().setGameMode(GameMode.SPECTATOR);
            }
        });

        eventNode().addListener(PlayerStartFlyingWithElytraEvent.class, playerStartFlyingWithElytraEvent -> {
            if(!isRunning) {
                playerStartFlyingWithElytraEvent.getPlayer().setFlyingWithElytra(false);
                return;
            }

            boost(playerStartFlyingWithElytraEvent.getPlayer());
        });
    }

    @Override
    protected void onLoad(@NotNull CompletableFuture<Void> callback) {
        Point spawnpoint = new Pos(vale.getXShiftAtZ(0), -46, 0);
        GeneratorUtils.iterateArea(spawnpoint.sub(5, 0, 5), spawnpoint.add(5, 0, 5), point -> setBlock(point, BlockPallet.STREET.rnd()));

        generateRing(ringSpacing);
        generateRing(ringSpacing * 2);
        callback.complete(null);
    }

    @Override
    protected void onStart() {
        getPlayers().forEach(player -> {
            player.getInventory().setEquipment(EquipmentSlot.CHESTPLATE, (byte) 0, ItemStack.of(Material.ELYTRA));
            for(int i = 0; i < 3; i++) {
                player.getInventory().setItemStack(i, ItemStack.builder(boostMaterial).customName(TranslatedComponent.byId("boost").getAssembled(player)).build());
            }
            addResetItemToPlayer(player);
        });
    }

    @Override
    protected void onPlayerMove(@NotNull PlayerMoveEvent playerMoveEvent) {
        Player player = playerMoveEvent.getPlayer();
        Point newPos = playerMoveEvent.getNewPosition();

        if(isBeforeBeginning && playerMoveEvent.getNewPosition().y() < getSpawn().y()) {
            player.teleport(getSpawn());
            return;
        }

        playerCheckpoints.putIfAbsent(player, new CheckPointData(ringSpacing, ringSpacing * 2));

        if(newPos.z() > generatedUntil - ringSpacing) {
            generateRing(generatedUntil + ringSpacing);
        }

        if(newPos.z() > playerCheckpoints.get(player).nextCheckpoint) {
            playerCheckpoints.put(player, playerCheckpoints.get(player).next(ringSpacing));
            boost(player);
        }

        if(newPos.y() > gameHeight - 5) {
            Point particlePoint = newPos.withY(gameHeight);
            ParticlePacket particle = new ParticlePacket(
                    Particle.WAX_ON,
                    particlePoint.blockX(),
                    particlePoint.blockY(),
                    particlePoint.withZ(z -> z+10).blockZ(),
                    20,
                    0,
                    30,
                    1f,
                    Math.toIntExact((long) NumberUtil.map(newPos.y(), gameHeight - 5, gameHeight, 50, 500))
            );
            player.sendPacket(particle);
        }

        if(getBlock(player.getPosition()).equals(Block.WATER)) {
            toCheckpoint(player);
        }

        if(newPos.z() > ringCount * ringSpacing) {
            getScore().insertResult(player);
            player.setGameMode(GameMode.SPECTATOR);
            player.setFlyingWithElytra(false);
        }
    }

    @Override
    public Pos getSpawn() {
        return new Pos(vale.getXShiftAtZ(0), -45, 0);
    }

    private void addResetItemToPlayer(Player p) {
        p.getInventory().setItemStack(8, ItemStack.builder(resetMaterial).customName(TranslatedComponent.byId("reset").getAssembled(p)).build());
    }

    private Point getRingPositionAtZ(int z) {
        return new Pos(vale.getXShiftAtZ(z), -45, z);
    }

    private CompletableFuture<Void> generateRing(int zPos) {
        if(zPos > ringCount * ringSpacing) return null;
        boolean isLast = (zPos == ringCount * ringSpacing);

        generatedUntil = zPos;
        AbsoluteBlockBatch batch = new AbsoluteBlockBatch();

        Point ringPos = getRingPositionAtZ(zPos);
        GeneratorUtils.iterateArea(
                ringPos.sub(100, 0, 0).withY(0),
                ringPos.add(100, 0, 0).withY(seaLevel),
                point -> batch.setBlock(point, Block.BARRIER)
        );
        GeneratorUtils.iterateArea(
                ringPos.sub(3, 3, 0),
                ringPos.add(3, 3, 0),
                point -> batch.setBlock(point, isLast ? Block.DIAMOND_BLOCK : ringMaterial.block())
        );
        GeneratorUtils.iterateArea(
                ringPos.sub(2, 2, 0),
                ringPos.add(2, 2, 0),
                point -> batch.setBlock(point, Block.AIR)
        );

        BatchUtil.loadAndApplyBatch(batch, this, () -> {});
        return null;
    }

    private void boost(Player player) {
        player.playSound(Sound.sound(SoundEvent.ENTITY_FIREWORK_ROCKET_LAUNCH, Sound.Source.VOICE, 1f, 1f));

        Vec playerVelocity = player.getPosition().direction();
        player.setVelocity(
                player.getVelocity().add(playerVelocity.mul(boostMultiplier))
                        .withY(playerVelocity.withY(v -> v * boostMultiplier).y())
        );
    }

    private void toCheckpoint(Player p) {
        Point checkpointPos = getRingPositionAtZ(playerCheckpoints.get(p).currentCheckpoint);
        p.setVelocity(Vec.ZERO);
        p.setFlyingWithElytra(false);
        p.teleport(Pos.fromPoint(checkpointPos).add(0.5, 0, 0.5));

        p.setFlying(true);
        p.setFlyingSpeed(0);

        new Countdown(TitleMessage.class)
                .countdown(
                        Audience.audience(p),
                        3,
                        countdownModifier ->
                                countdownModifier.message = new TitleMessage(
                                        Duration.ofMillis(300),
                                        Duration.ofMillis(700)
                                )
                                .subtitle(
                                        subtitleMessage ->
                                                subtitleMessage
                                                        .appendStatic(Component.text("Launch in ", NamedTextColor.DARK_GREEN))
                                                        .appendStatic(Component.text(countdownModifier.timeLeft, NamedTextColor.GREEN))
                                                        .appendStatic(Component.text(" seconds", NamedTextColor.DARK_GREEN))
                                )
                ).thenRun(() -> {
                    p.setFlying(false);
                    p.setFlyingSpeed(1);
                    p.setFlyingWithElytra(true);
                    boost(p);
                    addResetItemToPlayer(p);
                });
    }
}
