package de.viper.survivalplus.trade;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

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

public class TradeManager {

    private final SurvivalPlus plugin;
    private final Map<UUID, TradeSession> activeTrades = new HashMap<>();
    private final Map<UUID, UUID> pendingRequests = new HashMap<>();

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

    public void requestTrade(Player sender, Player target) {
        if (sender == null || target == null) return;
        if (isTrading(sender) || isTrading(target)) {
            sender.sendMessage(plugin.getLangConfig().getString("trade.already-trading", "§cEiner von euch ist bereits im Handel."));
            return;
        }

        if (sender.getUniqueId().equals(target.getUniqueId())) {
            sender.sendMessage(plugin.getLangConfig().getString("trade.with-yourself-not-allowed", "§cHandel mit dir selbst ist nicht erlaubt!"));
            return;
        }

        pendingRequests.put(target.getUniqueId(), sender.getUniqueId());

        String requestText = plugin.getLangConfig().getString("trade.request-text", "%player% möchte mit dir handeln. Klicke hier, um anzunehmen!")
                .replace("%player%", sender.getName());

        try {
            net.md_5.bungee.api.chat.TextComponent message = new net.md_5.bungee.api.chat.TextComponent(requestText);
            message.setColor(net.md_5.bungee.api.ChatColor.GREEN);
            message.setClickEvent(new net.md_5.bungee.api.chat.ClickEvent(net.md_5.bungee.api.chat.ClickEvent.Action.RUN_COMMAND, "/tradeaccept " + sender.getName()));
            target.spigot().sendMessage(message);
        } catch (Throwable ex) {
            target.sendMessage(requestText + " (/tradeaccept " + sender.getName() + ")");
        }

        sender.sendMessage(plugin.getLangConfig().getString("trade.request-sent", "§aHandelsanfrage an %player% gesendet.").replace("%player%", target.getName()));
    }

    public void acceptTrade(Player target, String requesterName) {
        if (target == null || requesterName == null) return;

        UUID pendingSenderUUID = pendingRequests.get(target.getUniqueId());
        if (pendingSenderUUID == null) {
            target.sendMessage(plugin.getLangConfig().getString("trade.no-pending-request", "§cKeine Handelsanfrage gefunden."));
            return;
        }

        Player sender = Bukkit.getPlayer(pendingSenderUUID);
        if (sender == null || !sender.isOnline()) {
            target.sendMessage(plugin.getLangConfig().getString("trade.player-not-online", "§cDieser Spieler ist nicht online!"));
            pendingRequests.remove(target.getUniqueId());
            return;
        }

        pendingRequests.remove(target.getUniqueId());
        startTrade(sender, target);
    }

    public void startTrade(Player sender, Player receiver) {
        if (isTrading(sender) || isTrading(receiver)) {
            sender.sendMessage(plugin.getLangConfig().getString("trade.already-trading", "§cEiner von euch ist bereits im Handel."));
            return;
        }

        // Neue Session starten
        TradeSession session = new TradeSession(plugin, sender, receiver, this);
        Bukkit.getPluginManager().registerEvents(session, plugin);

        activeTrades.put(sender.getUniqueId(), session);
        activeTrades.put(receiver.getUniqueId(), session);

        session.openInventory();

        sender.sendMessage(plugin.getLangConfig().getString("trade.started-sender", "§aTrade gestartet mit %player%").replace("%player%", receiver.getName()));
        receiver.sendMessage(plugin.getLangConfig().getString("trade.started-receiver", "§a%player% hat dich zu einem Trade eingeladen.").replace("%player%", sender.getName()));
    }

    public void endTrade(TradeSession session) {
        if (session == null) return;
        Player s = session.getSender();
        Player r = session.getReceiver();
        if (s != null) activeTrades.remove(s.getUniqueId());
        if (r != null) activeTrades.remove(r.getUniqueId());
        session.closeInventory();
    }

    public TradeSession getTrade(Player player) {
        if (player == null) return null;
        return activeTrades.get(player.getUniqueId());
    }

    public boolean isTrading(Player player) {
        if (player == null) return false;
        return activeTrades.containsKey(player.getUniqueId());
    }
}