package com.spaceshipproject;

import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataType;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/** Listener partage pour les SpaceshipGUI : clics, fermeture, et renommage par chat. */
public class SpaceshipGUIListener implements Listener {

    private static final Map<UUID, SpaceshipGuiPanel> OPEN_GUIS = new ConcurrentHashMap<>();
    private static final Map<UUID, Long> PENDING_RENAME = new ConcurrentHashMap<>();

    private final SpaceShipProject plugin;

    private SpaceshipGUIListener(SpaceShipProject plugin) {
        this.plugin = plugin;
    }

    public static void register(SpaceShipProject plugin) {
        plugin.getServer().getPluginManager().registerEvents(new SpaceshipGUIListener(plugin), plugin);
    }

    static void registerOpen(Player player, SpaceshipGUI gui) {
        OPEN_GUIS.put(player.getUniqueId(), gui);
    }

    static void registerOpenJump(Player player, SpaceJumpGUI gui) {
        OPEN_GUIS.put(player.getUniqueId(), gui);
    }

    static void registerPendingRename(Player player, Spaceship ship) {
        PENDING_RENAME.put(player.getUniqueId(), ship.getId());
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
    public void onInventoryClick(InventoryClickEvent event) {
        if (!(event.getWhoClicked() instanceof Player)) return;
        Inventory top = event.getView().getTopInventory();
        if (!(top.getHolder() instanceof SpaceshipGUIHolder holder)) return;
        event.setCancelled(true);
        if (event.getClickedInventory() != null && event.getClickedInventory() == top) {
            holder.getPanel().handleClick(event);
        }
    }

    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
    public void onInventoryDrag(InventoryDragEvent event) {
        if (!(event.getWhoClicked() instanceof Player)) return;
        Inventory top = event.getView().getTopInventory();
        if (!(top.getHolder() instanceof SpaceshipGUIHolder)) return;
        event.setCancelled(true);
    }

    @EventHandler
    public void onInventoryClose(InventoryCloseEvent event) {
        if (!(event.getPlayer() instanceof Player player)) return;
        if (event.getInventory().getHolder() instanceof SpaceshipGUIHolder) {
            OPEN_GUIS.remove(player.getUniqueId());
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onChat(AsyncChatEvent event) {
        Player player = event.getPlayer();
        Long shipId = PENDING_RENAME.remove(player.getUniqueId());
        if (shipId == null) return;

        String message = PlainTextComponentSerializer.plainText().serialize(event.message()).trim();
        event.setCancelled(true);

        Bukkit.getScheduler().runTask(plugin, () -> {
            if (message.equalsIgnoreCase("cancel") || message.isEmpty()) {
                player.sendMessage(plugin.getConfigManager().prefix()
                        + ConfigManager.color("&7Renommage annule."));
                return;
            }
            String clean = message.length() > 32 ? message.substring(0, 32) : message;
            Spaceship ship = plugin.getDatabaseManager().getSpaceship(shipId);
            if (ship == null || !ship.getOwnerUuid().equals(player.getUniqueId())) {
                player.sendMessage(plugin.getConfigManager().prefix()
                        + ConfigManager.color("&cImpossible de renommer ce spaceship."));
                return;
            }
            ship.setName(clean);
            plugin.getDatabaseManager().updateSpaceship(ship);

            // Met a jour la telecommande dans la main si elle est presente
            ItemStack mainHand = player.getInventory().getItemInMainHand();
            if (plugin.getRemoteManager().isRemote(mainHand)
                    && mainHand.getItemMeta() != null
                    && shipId.equals(mainHand.getItemMeta().getPersistentDataContainer()
                            .get(plugin.getRemoteManager().getShipIdKey(), PersistentDataType.LONG))) {
                plugin.getRemoteManager().refreshRemote(mainHand, ship);
                player.getInventory().setItemInMainHand(mainHand);
            }

            player.sendMessage(plugin.getConfigManager().prefix()
                    + ConfigManager.color("&aSpaceship renomme : &b" + clean));
        });
    }
}
