package hu.jgj52.pvpcore.Listeners;

import hu.jgj52.pvpcore.Main;
import hu.jgj52.pvpcore.Utils.Database;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.Title;
import org.bukkit.*;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

public class PlayerListener implements Listener {
    private final Main plugin;

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

    @EventHandler
    public void onJoin(PlayerJoinEvent event) throws ExecutionException, InterruptedException {
        Database.QueryResult result = plugin.db.from("pvpcore_players")
                .eq("uuid", event.getPlayer().getUniqueId())
                .execute()
                .get();
        Map<String, Object> data = new HashMap<>();
        if (result.isEmpty()) {
            data.put("uuid", event.getPlayer().getUniqueId());
            data.put("admin", event.getPlayer().hasPermission("pvpcore.admin"));
            plugin.db.from("pvpcore_players").insert(data);
        } else {
            data.put("admin", event.getPlayer().hasPermission("pvpcore.admin"));
            plugin.db.from("pvpcore_players").eq("uuid", event.getPlayer().getUniqueId()).update(data);
        }
        plugin.tpToSpawn(event.getPlayer());
    }

    @EventHandler
    public void onLeave(PlayerQuitEvent e) throws ExecutionException, InterruptedException {
        Player player = e.getPlayer();
        for (String key : plugin.metadatas) {
            for (MetadataValue value : player.getMetadata(key)) {
                if (value.getOwningPlugin() == plugin) {
                    player.removeMetadata(key, plugin);
                    break;
                }
            }
        }
        boolean isEnemy = false;
        Database.QueryResult result = plugin.db.from("pvpcore_duels").eq("player", player.getUniqueId()).execute().get();
        if (result.isEmpty()) {
            result = plugin.db.from("pvpcore_duels").eq("enemy", player.getUniqueId()).execute().get();
            isEnemy = true;
        }


        if (!result.isEmpty()) {
            Map<String, Object> row = result.data.get(0);
            Player enemy = Bukkit.getPlayer(UUID.fromString(isEnemy ? row.get("player").toString() : row.get("enemy").toString()));
            enemy.getInventory().clear();
            Location playerLoc = player.getLocation();

            Title winnerTitle = Title.title(
                    Component.text("§6🗡 §eMegnyerted a párbajt!"),
                    Component.empty(),
                    Title.Times.times(Duration.ofMillis(500), Duration.ofSeconds(3), Duration.ofMillis(1000))
            );

            for (int i = 0; i < 3; i++) {
                int delay = i * 10;
                Bukkit.getScheduler().runTaskLater(plugin, () -> {
                    Firework firework = playerLoc.getWorld().spawn(playerLoc, Firework.class);
                    FireworkMeta meta = firework.getFireworkMeta();

                    FireworkEffect effect = FireworkEffect.builder()
                            .with(FireworkEffect.Type.BURST)
                            .withColor(
                                    Color.fromRGB(2437522),
                                    Color.fromRGB(14602026),
                                    Color.fromRGB(6719955)
                            )
                            .build();

                    meta.addEffect(effect);
                    meta.setPower((int) 0.5);
                    firework.setFireworkMeta(meta);
                }, delay);
            }

            enemy.showTitle(winnerTitle);

            Bukkit.getScheduler().runTaskLater(plugin, () -> {
                try {
                    plugin.tpToSpawn(enemy);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }, 60L);

            Map<String, Object> data = new HashMap<>();
            data.put("player", row.get("player"));
            data.put("enemy", row.get("enemy"));
            data.put("ft", row.get("ft"));
            data.put("kit", row.get("kit"));
            data.put("winner", enemy.getUniqueId());
            plugin.db.from("pvpcore_duel_logs").insert(data);
            plugin.db.from("pvpcore_duels").eq(isEnemy ? "enemy" : "player", player.getUniqueId()).eq(isEnemy ? "player" : "enemy", enemy.getUniqueId()).delete();
        }
    }
}
