package hu.jgj52.pvpcore.Commands;

import hu.jgj52.pvpcore.Main;
import hu.jgj52.pvpcore.Utils.Database;
import hu.jgj52.pvpcore.Utils.Kits;
import hu.jgj52.pvpcore.Utils.SchematicManager;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.Title;
import java.time.Duration;

import java.util.*;
import java.util.concurrent.ExecutionException;

import static java.util.Collections.min;

public class AcceptDuelCommand implements CommandExecutor, TabCompleter {
    private final Main plugin;

    public AcceptDuelCommand(Main plugin) {
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
        if (sender instanceof Player player) {
            if (args.length != 1) {
                player.sendMessage("§cHasználat: /acceptduel <játékos>");
                return true;
            }


            Database.QueryResult reqResult = null;
            try {
                reqResult = plugin.db.from("pvpcore_duel_requests").eq("player", Objects.requireNonNull(Bukkit.getPlayer(args[0])).getUniqueId()).eq("enemy", player.getUniqueId()).execute().get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }

            Map<String, Object> row = reqResult.data.get(0);

            Player enemy = Bukkit.getPlayer(args[0]);
            if (enemy == null) {
                player.sendMessage("§cA megadott játékos nem található.");
                return true;
            }

            if (reqResult.isEmpty()) {
                player.sendMessage("§cNincs párbajkérelmed ettől a játékostól.");
                return true;
            }

            Kits kitManager = new Kits(plugin);
            SchematicManager schematic = new SchematicManager(plugin);

            String gamemode = row.get("kit").toString();

            Database.QueryResult result = null;
            try {
                result = plugin.db.from("pvpcore_kits")
                        .eq("name", gamemode)
                        .execute()
                        .get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }

            Map<String, Object> kitRow = result.data.get(0);

            player.getInventory().clear();
            enemy.getInventory().clear();
            World world = Bukkit.getWorld("arenas");
            boolean survival = Boolean.parseBoolean(kitRow.get("survival").toString());
            String arena = kitRow.get("arena").toString();
            int x = Integer.parseInt(kitRow.get("id").toString()) * 1000;
            int y = 0;
            int z;

            if (plugin.usedArenas.isEmpty()) {
                z = 0;
            } else {
                z = min(plugin.usedArenas) - 1000;
            }

            plugin.usedArenas.add(z);

            schematic.placeSchematic(world, x, y, z, arena, true);
            Location playerLoc = new Location(world, x + 20.5, y, z + 0.5, 90, 0);
            Location enemyLoc = new Location(world, x - 20.5, y, z + 0.5, -90, 0);

            for (PotionEffect potionEffect : player.getActivePotionEffects()) {
                player.removePotionEffect(potionEffect.getType());
            }
            for (PotionEffect potionEffect : enemy.getActivePotionEffects()) {
                enemy.removePotionEffect(potionEffect.getType());
            }
            player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20, 1), true);
            enemy.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20, 1), true);
            player.teleport(playerLoc);
            enemy.teleport(enemyLoc);
            try {
                player.getInventory().setContents(kitManager.getKit(gamemode, player, false));
                enemy.getInventory().setContents(kitManager.getKit(gamemode, enemy, false));
            } catch (ExecutionException | InterruptedException e) {
                throw new RuntimeException(e);
            }
            player.setHealth(20D);
            enemy.setHealth(20D);
            player.setFoodLevel(20);
            enemy.setFoodLevel(20);
            player.setSaturation(5);
            enemy.setSaturation(5);
            player.setGameMode(survival ? GameMode.SURVIVAL : GameMode.ADVENTURE);
            enemy.setGameMode(survival ? GameMode.SURVIVAL : GameMode.ADVENTURE);

            Map<String, Object> duelData = new HashMap<>();
            duelData.put("player", enemy.getUniqueId());
            duelData.put("enemy", player.getUniqueId());
            duelData.put("ft", row.get("ft"));
            duelData.put("kit", gamemode);
            duelData.put("started", System.currentTimeMillis());

            plugin.db.from("pvpcore_duels").insert(duelData);
            plugin.db.from("pvpcore_duel_requests").eq("player", Objects.requireNonNull(Bukkit.getPlayer(args[0])).getUniqueId()).eq("enemy", player.getUniqueId()).delete();

            player.setMetadata("Frozen", new FixedMetadataValue(plugin, true));
            enemy.setMetadata("Frozen", new FixedMetadataValue(plugin, true));

            new BukkitRunnable() {
                int countdown = 3;

                @Override
                public void run() {
                    if (countdown > 0) {
                        Component titleText = Component.text(String.valueOf(countdown), NamedTextColor.AQUA);
                        Title title = Title.title(
                                titleText,
                                Component.empty(),
                                Title.Times.times(Duration.ZERO, Duration.ofSeconds(1), Duration.ZERO)
                        );
                        player.showTitle(title);
                        enemy.showTitle(title);
                        countdown--;
                    } else {
                        Title startTitle = Title.title(
                                Component.text("§eA párbaj megkezdődött!"),
                                Component.empty(),
                                Title.Times.times(Duration.ZERO, Duration.ofSeconds(2), Duration.ofSeconds(1))
                        );
                        player.showTitle(startTitle);
                        enemy.showTitle(startTitle);
                        player.removeMetadata("Frozen", plugin);
                        enemy.removeMetadata("Frozen", plugin);
                        cancel();
                    }
                }
            }.runTaskTimer(plugin, 0L, 20L);

        }

        return true;
    }


    @Override
    public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
        return List.of();
    }
}
