package de.viper.survivalplus.listeners;

import de.viper.survivalplus.SurvivalPlus;
import net.md_5.bungee.api.ChatColor;
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.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NickLoadListener implements Listener {

    private final SurvivalPlus plugin;
    private static final Pattern HEX_PATTERN = Pattern.compile("#[a-fA-F0-9]{6}");

    public NickLoadListener(SurvivalPlus plugin) {
        this.plugin = plugin;
    }

    @EventHandler(priority = EventPriority.LOWEST)
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();

        // Immer die Standard-Join-Message unterdrücken — wir senden eine einzelne kontrollierte Nachricht später
        event.setJoinMessage(null);

        String rawNick = plugin.getNicknamesConfig().getString(player.getUniqueId().toString());
        if (rawNick != null && !rawNick.isEmpty()) {
            String coloredNick = translateColors(rawNick);
            String plainNick = ChatColor.stripColor(coloredNick);

            // Kurz: DisplayName jetzt auf echten Namen lassen, damit andere Plugins / Bukkit intern konsistent sind.
            player.setDisplayName(player.getName());

            // In 1 Tick: DisplayName für Chat setzen UND die Join-Nachricht EINMAL manuell versenden
            Bukkit.getScheduler().runTask(plugin, () -> {
                // Chat-Display: [Nick]
                player.setDisplayName("§f[" + coloredNick + "§f]");

                // Nachricht an alle Spieler senden (keine Doppelung, weil wir event.setJoinMessage(null) gesetzt haben)
                String message = coloredNick + " §ejoined the game";
                for (Player p : Bukkit.getOnlinePlayers()) {
                    p.sendMessage(message);
                }

                // Log in Konsole (sauber, ohne Farb-Codes)
                plugin.getLogger().info(plainNick + " joined the game");
            });
        } else {
            // Kein Nick vorhanden -> benutze Standardverhalten, aber ebenfalls manuell, um Doppelungen zu verhindern
            player.setDisplayName(player.getName());
            Bukkit.getScheduler().runTask(plugin, () -> {
                String message = player.getName() + " §ejoined the game";
                for (Player p : Bukkit.getOnlinePlayers()) {
                    p.sendMessage(message);
                }
                plugin.getLogger().info(player.getName() + " joined the game");
            });
        }
    }

    @EventHandler(priority = EventPriority.LOWEST)
    public void onPlayerQuit(PlayerQuitEvent event) {
        Player player = event.getPlayer();

        // Standard-Quit-Message unterdrücken
        event.setQuitMessage(null);

        String rawNick = plugin.getNicknamesConfig().getString(player.getUniqueId().toString());
        if (rawNick != null && !rawNick.isEmpty()) {
            String coloredNick = translateColors(rawNick);
            String plainNick = ChatColor.stripColor(coloredNick);

            // Sende Quit-Nachricht einmal manuell
            String msg = coloredNick + " §eleft the game";
            for (Player p : Bukkit.getOnlinePlayers()) {
                p.sendMessage(msg);
            }
            plugin.getLogger().info(plainNick + " left the game");
        } else {
            String msg = player.getName() + " §eleft the game";
            for (Player p : Bukkit.getOnlinePlayers()) {
                p.sendMessage(msg);
            }
            plugin.getLogger().info(player.getName() + " left the game");
        }
    }

    private String translateColors(String input) {
        String withLegacy = org.bukkit.ChatColor.translateAlternateColorCodes('&', input);
        Matcher matcher = HEX_PATTERN.matcher(withLegacy);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String hexCode = matcher.group();
            String replacement = ChatColor.of(hexCode).toString();
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
