package de.teleportsuite.managers;

import de.teleportsuite.TeleportSuite;
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;
    // Pending TPA requests: requester -> target
    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<>();
    // Saved "before teleport" locations (for /back)
    private final Map<UUID, TeleportLocation> pendingBackLocations = new HashMap<>();

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

    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;

        // Check cooldown
        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();

        if (!dest.isLocalServer(localServer)) {
            // BungeeCord-Teleport
            if (plugin.getBungeeMessenger() != null) {
                plugin.getBungeeMessenger().connectToServer(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("§cZielwelt nicht gefunden!");
            return;
        }

        // Save last location to database
        plugin.getDatabaseManager().saveLastLocation(player.getUniqueId(),
                new TeleportLocation(player.getLocation(), localServer));

        player.teleport(loc);
        cooldowns.put(player.getUniqueId(), System.currentTimeMillis());
        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);
    }

    // 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);
    }

    public boolean acceptTpa(Player target) {
        UUID requester = null;
        for (Map.Entry<UUID, UUID> entry : tpaRequests.entrySet()) {
            if (entry.getValue().equals(target.getUniqueId())) {
                requester = entry.getKey();
                break;
            }
        }
        if (requester == null) return false;

        Player from = Bukkit.getPlayer(requester);
        tpaRequests.remove(requester);
        requestTimestamps.remove(requester);

        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;
    }

    public boolean denyTpa(Player target) {
        UUID requester = null;
        for (Map.Entry<UUID, UUID> entry : tpaRequests.entrySet()) {
            if (entry.getValue().equals(target.getUniqueId())) {
                requester = entry.getKey();
                break;
            }
        }
        if (requester == null) return false;

        Player from = Bukkit.getPlayer(requester);
        tpaRequests.remove(requester);
        requestTimestamps.remove(requester);

        if (from != null && from.isOnline())
            from.sendMessage(plugin.getConfigManager().getMessage("tpa-denied", "player", target.getName()));
        return true;
    }
}
