package de.viper.survivalplus.commands;

import de.viper.survivalplus.Manager.Warp;
import de.viper.survivalplus.Manager.WarpManager;
import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.*;
import java.util.stream.Collectors;

public class WarpsCommand implements CommandExecutor {

    private final SurvivalPlus plugin;
    private final WarpManager warpManager;

    public WarpsCommand(SurvivalPlus plugin, WarpManager warpManager) {
        this.plugin = plugin;
        this.warpManager = warpManager;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(plugin.getMessage("warp.only_players"));
            return true;
        }
        Player player = (Player) sender;

        Map<String, List<Warp>> warpsByOwner = warpManager.getWarps().values().stream()
                .collect(Collectors.groupingBy(Warp::getOwner));

        List<String> ownersSorted = new ArrayList<>(warpsByOwner.keySet());
        Collections.sort(ownersSorted);

        int totalWarps = warpManager.getWarps().size();
        int size = ((totalWarps + 8) / 9) * 9;
        if (size < 27) size = 27; // mindestens 27 Slots

        Inventory inv = Bukkit.createInventory(null, size, ChatColor.GOLD + "Player Warps");

        int slot = 0;
        for (String owner : ownersSorted) {
            for (Warp warp : warpsByOwner.get(owner)) {
                if (slot >= size) break;

                ItemStack item = warp.getItem().clone();
                item.setAmount(1);
                ItemMeta meta = item.getItemMeta();
                if (meta != null) {
                    meta.setDisplayName(ChatColor.YELLOW + warp.getName());
                    List<String> lore = new ArrayList<>();
                    lore.add(ChatColor.GRAY + "Owner: " + warp.getOwner());
                    lore.add(ChatColor.GRAY + "World: " + warp.getWorldName());
                    meta.setLore(lore);
                    meta.setUnbreakable(true);
                    item.setItemMeta(meta);
                }

                inv.setItem(slot++, item);
            }
            if (slot >= size) break;
        }

        player.openInventory(inv);
        return true;
    }
}
