package de.teleportsuite.managers;

import de.teleportsuite.TeleportSuite;
import de.teleportsuite.bungeemessaging.BungeeMessenger;
import de.teleportsuite.models.TeleportLocation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;

import java.util.*;

public class TeleportManager {
    private final TeleportSuite plugin;
    // Same-server pending TPA: requesterUUID → targetUUID
    private final Map<UUID, UUID> tpaRequests = new HashMap<>();
    private final Map<UUID, Long> requestTimestamps = new HashMap<>();
    // Cooldowns
    private final Map<UUID, Long> cooldowns = new HashMap<>();
    // Warmup tasks
    private final Map<UUID, Integer> warmupTasks = new HashMap<>();
    // Back-locations (saved before every teleport)
    private final Map<UUID, TeleportLocation> pendingBackLocations = new HashMap<>();

    public TeleportManager(TeleportSuite plugin) { this.plugin = plugin; }

    // -------------------------------------------------------------------------
    // Main teleport entry point
    // -------------------------------------------------------------------------

    public void teleport(Player player, TeleportLocation destination) {
        teleport(player, destination, true);
    }

    public void teleport(Player player, TeleportLocation destination, boolean saveBack) {
        int delay = plugin.getConfigManager().getTeleportDelay();
        if (player.hasPermission("teleportsuite.nodelay")) delay = 0;

        if (!player.hasPermission("teleportsuite.nocooldown")) {
            long cooldownMs = plugin.getConfigManager().getTeleportCooldown() * 1000L;
            long lastTp = cooldowns.getOrDefault(player.getUniqueId(), 0L);
            if (System.currentTimeMillis() - lastTp < cooldownMs) {
                long remaining = (cooldownMs - (System.currentTimeMillis() - lastTp)) / 1000;
                player.sendMessage(plugin.getConfigManager().getMessage(
                        "teleport-cooldown", "seconds", String.valueOf(remaining)));
                return;
            }
        }

        if (saveBack) {
            pendingBackLocations.put(player.getUniqueId(),
                    new TeleportLocation(player.getLocation(), plugin.getConfigManager().getServerName()));
        }

        if (delay <= 0) {
            executeTeleport(player, destination);
            return;
        }

        player.sendMessage(plugin.getConfigManager().getMessage(
                "teleport-warmup", "seconds", String.valueOf(delay)));
        Location startLoc = player.getLocation().clone();

        int taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
            if (plugin.getConfigManager().cancelOnMove()) {
                Location now = player.getLocation();
                if (Math.abs(now.getX() - startLoc.getX()) > 0.5
                        || Math.abs(now.getZ() - startLoc.getZ()) > 0.5) {
                    player.sendMessage(plugin.getConfigManager().getMessage("teleport-cancelled"));
                    warmupTasks.remove(player.getUniqueId());
                    return;
                }
            }
            executeTeleport(player, destination);
            warmupTasks.remove(player.getUniqueId());
        }, delay * 20L);

        warmupTasks.put(player.getUniqueId(), taskId);
    }

    private void executeTeleport(Player player, TeleportLocation dest) {
        String localServer = plugin.getConfigManager().getServerName();

        // Save last location + apply cooldown always (also for cross-server)
        plugin.getDatabaseManager().saveLastLocation(player.getUniqueId(),
                new TeleportLocation(player.getLocation(), localServer));
        cooldowns.put(player.getUniqueId(), System.currentTimeMillis());

        if (!dest.isLocalServer(localServer)) {
            // Cross-server: delegate completely to the Bungee plugin.
            // It will call sender.connect() and then send TP_PLAYERTOPOSITION.
            BungeeMessenger bm = plugin.getBungeeMessenger();
            if (bm != null) {
                bm.teleportToPosition(player, dest.getServer(), dest.getWorld(),
                        dest.getX(), dest.getY(), dest.getZ(), dest.getYaw(), dest.getPitch());
                player.sendMessage(plugin.getConfigManager().getMessage("teleport-success"));
            }
            return;
        }

        Location loc = dest.toBukkitLocation();
        if (loc == null || loc.getWorld() == null) {
            player.sendMessage("§cFehler: Zielwelt §6" + dest.getWorld() + "§c nicht gefunden!"
                    + " Ist der Spawn auf diesem Server gesetzt?");
            plugin.getLogger().warning("Teleport fehlgeschlagen: Welt '" + dest.getWorld()
                    + "' fuer Spieler " + player.getName() + " nicht geladen.");
            return;
        }

        player.teleport(loc);
        player.sendMessage(plugin.getConfigManager().getMessage("teleport-success"));
    }

    public void cancelWarmup(UUID uuid) {
        Integer taskId = warmupTasks.remove(uuid);
        if (taskId != null) Bukkit.getScheduler().cancelTask(taskId);
    }

    public TeleportLocation getBackLocation(UUID uuid) {
        return pendingBackLocations.get(uuid);
    }

    // -------------------------------------------------------------------------
    // Same-server TPA
    // -------------------------------------------------------------------------

    public void sendTpaRequest(Player from, Player to) {
        tpaRequests.put(from.getUniqueId(), to.getUniqueId());
        requestTimestamps.put(from.getUniqueId(), System.currentTimeMillis());

        to.sendMessage(plugin.getConfigManager().getMessage("tpa-received", "player", from.getName()));
        from.sendMessage(plugin.getConfigManager().getMessage("tpa-sent", "player", to.getName()));

        int timeout = plugin.getConfigManager().getRequestTimeout();
        Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {
            if (tpaRequests.containsKey(from.getUniqueId())) {
                tpaRequests.remove(from.getUniqueId());
                requestTimestamps.remove(from.getUniqueId());
                if (from.isOnline()) {
                    from.sendMessage(plugin.getConfigManager().getMessage("tpa-expired"));
                }
            }
        }, timeout * 20L);
    }

    // -------------------------------------------------------------------------
    // Cross-server TPA — all state lives on the Bungee plugin now;
    // Spigot just sends the right payload and handles local accept/deny.
    // -------------------------------------------------------------------------

    /**
     * Called by TpaCommand when the target player is NOT on this server.
     * Bungee will manage the pending state and route all messages.
     */
    public void sendCrossServerTpaRequest(Player from, String targetName) {
        BungeeMessenger bm = plugin.getBungeeMessenger();
        if (bm == null) {
            from.sendMessage(plugin.getConfigManager().getMessage("player-not-found", "player", targetName));
            return;
        }
        bm.sendTpaRequest(
                from, targetName, "TPTO",
                plugin.getConfigManager().getMessage("tpa-received", "player", from.getName()),
                plugin.getConfigManager().getMessage("tpa-sent",     "player", targetName));
    }

    /** Called by TpAcceptCommand — handles both same-server and cross-server. */
    public boolean acceptTpa(Player target) {
        // Same-server accept
        UUID requesterUUID = null;
        for (Map.Entry<UUID, UUID> entry : tpaRequests.entrySet()) {
            if (entry.getValue().equals(target.getUniqueId())) {
                requesterUUID = entry.getKey();
                break;
            }
        }
        if (requesterUUID != null) {
            Player from = Bukkit.getPlayer(requesterUUID);
            tpaRequests.remove(requesterUUID);
            requestTimestamps.remove(requesterUUID);
            if (from != null && from.isOnline()) {
                from.sendMessage(plugin.getConfigManager().getMessage("tpa-accepted", "player", target.getName()));
                teleport(from, new TeleportLocation(target.getLocation(),
                        plugin.getConfigManager().getServerName()));
            }
            return true;
        }

        // Cross-server accept — tell Bungee, it has the pending state
        BungeeMessenger bm = plugin.getBungeeMessenger();
        if (bm == null) return false;
        bm.sendTpaAccept(target, null,
                plugin.getConfigManager().getMessage("tpa-request-not-found"));
        return true;
    }

    /** Called by TpDenyCommand — handles both same-server and cross-server. */
    public boolean denyTpa(Player target) {
        // Same-server deny
        UUID requesterUUID = null;
        for (Map.Entry<UUID, UUID> entry : tpaRequests.entrySet()) {
            if (entry.getValue().equals(target.getUniqueId())) {
                requesterUUID = entry.getKey();
                break;
            }
        }
        if (requesterUUID != null) {
            Player from = Bukkit.getPlayer(requesterUUID);
            tpaRequests.remove(requesterUUID);
            requestTimestamps.remove(requesterUUID);
            if (from != null && from.isOnline()) {
                from.sendMessage(plugin.getConfigManager().getMessage("tpa-denied", "player", target.getName()));
            }
            return true;
        }

        // Cross-server deny
        BungeeMessenger bm = plugin.getBungeeMessenger();
        if (bm == null) return false;
        bm.sendTpaDeny(target, null,
                plugin.getConfigManager().getMessage("tpa-denied", "player", target.getName()));
        return true;
    }
}
