package hu.jgj52.pvpcore.Listeners;

import hu.jgj52.pvpcore.Main;
import hu.jgj52.pvpcore.Utils.Database;
import hu.jgj52.pvpcore.Utils.Kits;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.postgresql.util.PGobject;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class KitListener implements Listener {
    private final Main plugin;
    private final Kits kitsUtil;

    public KitListener(Main plugin) {
        this.plugin = plugin;
        this.kitsUtil = new Kits(plugin);
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) throws ExecutionException, InterruptedException, SQLException {
        if (!(event.getWhoClicked() instanceof Player player)) return;

        if (event.getClickedInventory() == event.getView().getTopInventory()
                && event.getView().title().equals(Component.text("Kit Editor"))) {
            event.setCancelled(true);

            boolean saveSlot = (0 <= event.getSlot() && event.getSlot() <= 2)
                    || (9 <= event.getSlot() && event.getSlot() <= 11)
                    || (18 <= event.getSlot() && event.getSlot() <= 20);

            boolean cancelSlot = (6 <= event.getSlot() && event.getSlot() <= 8)
                    || (15 <= event.getSlot() && event.getSlot() <= 17)
                    || (24 <= event.getSlot() && event.getSlot() <= 26);

            if (saveSlot) {
                String gamemode = event.getClickedInventory().getItem(13).getItemMeta().getDisplayName().split(" ")[2];

                ItemStack[] kit = kitsUtil.getKit(gamemode, player, true);

                String base64Inv = Kits.itemStackArrayToBase64(player.getInventory().getContents());

                Database.QueryResult plResult = plugin.db.from("pvpcore_players")
                        .eq("uuid", player.getUniqueId())
                        .execute()
                        .get();

                Map<String, String> playerKits;
                if (!plResult.isEmpty()) {
                    Map<String, Object> playerRow = plResult.data.get(0);
                    Object kitsObj = playerRow.get("kits");
                    if (kitsObj != null) {
                        String playerKitsStr = kitsObj instanceof PGobject pg ? pg.getValue() : kitsObj.toString();
                        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<String, String>>() {}.getType();
                        playerKits = new com.google.gson.Gson().fromJson(playerKitsStr, type);
                    } else {
                        playerKits = new HashMap<>();
                    }
                } else {
                    playerKits = new HashMap<>();
                }

                Database.QueryResult result = plugin.db.from("pvpcore_kits")
                        .eq("name", gamemode)
                        .execute()
                        .get();

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

                playerKits.put(kitRow.get("id").toString(), base64Inv);

                Map<String, Object> data = new HashMap<>();
                PGobject jsonObj = new PGobject();
                jsonObj.setType("json");
                jsonObj.setValue(new com.google.gson.Gson().toJson(playerKits));
                data.put("kits", jsonObj);

                plugin.db.from("pvpcore_players")
                        .eq("uuid", player.getUniqueId())
                        .update(data)
                        .thenAccept(r -> player.sendMessage("§aA kit el lett mentve."))
                        .exceptionally(ex -> {
                            ex.printStackTrace();
                            player.sendMessage("§cHiba történt a kit mentése közben.");
                            return null;
                        });

                player.closeInventory();
            } else if (cancelSlot) {
                player.closeInventory();
                player.sendMessage("§cA kited nem került mentésre.");
            }
        }
    }

    @EventHandler
    public void onInventoryClose(InventoryCloseEvent event) {
        if (!(event.getPlayer() instanceof Player player)) return;
        if (event.getInventory() == event.getView().getTopInventory()
                && event.getView().title().equals(Component.text("Kit Editor"))) {
            player.getInventory().clear();
        }
    }
}
