package hu.jgj52.pvpcore.Listeners;

import hu.jgj52.pvpcore.Main;
import hu.jgj52.pvpcore.Utils.Database;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import org.bukkit.inventory.meta.ItemMeta;

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

public class DuelRequestListener implements Listener {
    private final Main plugin;

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

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (!(event.getWhoClicked() instanceof Player player)) return;

        if (event.getView().getTitle().equals("§9\uD83D\uDDE1 Játékmód Választás")) {
            event.setCancelled(true);
        }
    }

    @EventHandler
    public void onDuelRequest(InventoryClickEvent e) throws ExecutionException, InterruptedException {
        Player player = (Player) e.getWhoClicked();

        if (!e.getView().getTitle().equals("§9\uD83D\uDDE1 Játékmód Választás")) return;

        ItemStack clickedItem = e.getCurrentItem();
        if (clickedItem == null || clickedItem.getType() == Material.AIR) return;

        if (clickedItem.getType() == Material.RED_STAINED_GLASS_PANE || clickedItem.getType() == Material.BLUE_STAINED_GLASS_PANE) return;

        if (clickedItem.getType() == Material.PAPER) {
            int count = clickedItem.getAmount();
            if (e.getClick() == ClickType.LEFT) {
                count++;
            } else if (e.getClick() == ClickType.RIGHT) {
                count--;
            }
            clickedItem.setAmount(count);
            return;
        }

        if (e.getClick() != ClickType.LEFT) return;

        Database.QueryResult result = plugin.db.from("pvpcore_duel_requests").eq("player", player.getUniqueId()).execute().get();

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

        if (!result.isEmpty()) {
            e.setCancelled(true);

            Player target = Bukkit.getPlayer(UUID.fromString(row.get("enemy").toString()));

            if (target == null) {
                player.sendMessage("§cA meghívott játékos nincs jelen a szerveren.");
                return;
            }

            String gamemode = ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName().toLowerCase());

            Map<String, Object> data = new HashMap<>();
            data.put("kit", gamemode);
            data.put("ft", e.getView().getInventory(0).getItem(4).getAmount());
            plugin.db.from("pvpcore_duel_requests").update(data);

            TextComponent accept = new TextComponent("§a[✔ Elfogadás]");
            accept.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/acceptduel " + player.getName()));
            accept.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
                    new ComponentBuilder("§a✔ Nyomj rá az elfogadáshoz!").create()));

            TextComponent decline = new TextComponent("§c[❌ Elutasítás]");
            decline.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/denyduel " + player.getName()));
            decline.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
                    new ComponentBuilder("§c❌ Nyomj rá az elutasításhoz!").create()));

            TextComponent info = new TextComponent("§7ℹ");
            info.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
                    new ComponentBuilder("§7Játékmód: §a" + ChatColor.stripColor(clickedItem.getItemMeta().getDisplayName()) + "\n")
                            .append("§7Aréna: §aFootball\n")
                            .append("§7Ellenfél: §e" + player.getName() + "\n")
                            .append("§7Opciók:\n")
                            .append("§8- §7Kör: §e1\n")
                            .create()));

            TextComponent fullMessage = new TextComponent();
            fullMessage.addExtra(accept);
            fullMessage.addExtra(" ");
            fullMessage.addExtra(decline);
            fullMessage.addExtra(" ");
            fullMessage.addExtra(info);

            target.sendMessage("§8-----------------------------------------------------");
            target.sendMessage("§c\uD83D\uDDE1 §e" + player.getName() + " §7küldött egy " + clickedItem.getItemMeta().getDisplayName().toLowerCase() + " §7párbaj kérést!");
            target.sendMessage(" ");
            target.spigot().sendMessage(fullMessage);
            target.sendMessage("§8-----------------------------------------------------");

            player.closeInventory();
        }
    }
}