package de.viper.survivalplus.commands;

import de.viper.survivalplus.SurvivalPlus;
import org.bukkit.Bukkit;
import org.bukkit.Location;
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 org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;

import java.util.ArrayList;
import java.util.List;

public class HomeCommand implements CommandExecutor {
    private final SurvivalPlus plugin;

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

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(plugin.getLangConfig().getString("player-only", "§cDieser Befehl ist nur für Spieler!"));
            return true;
        }

        Player player = (Player) sender;
        FileConfiguration lang = plugin.getLangConfig();
        FileConfiguration homes = plugin.getHomesConfig();
        String commandName = command.getName().toLowerCase();

        if (commandName.equals("sethome")) {
            if (!player.hasPermission("survivalplus.homes.set")) {
                player.sendMessage(lang.getString("no-permission", "§cDu hast keine Berechtigung für diesen Befehl!"));
                return true;
            }

            if (args.length != 1) {
                player.sendMessage(lang.getString("sethome.usage", "§cVerwendung: /sethome <name>"));
                return true;
            }

            String homeName = args[0].toLowerCase();
            if (!homeName.matches("[a-z0-9_]+")) {
                player.sendMessage(lang.getString("sethome.invalid-name", "§cDer Home-Name darf nur Buchstaben, Zahlen und Unterstriche enthalten!"));
                return true;
            }

            String path = "homes." + player.getUniqueId() + "." + homeName;
            if (homes.contains(path)) {
                player.sendMessage(lang.getString("sethome.already-exists", "§cEin Home mit diesem Namen existiert bereits!"));
                return true;
            }

            int maxHomes = player.hasPermission("survivalplus.homes.unlimited") ? Integer.MAX_VALUE : plugin.getConfig().getInt("max-homes", 3);
            int currentHomes = homes.getConfigurationSection("homes." + player.getUniqueId()) != null ?
                homes.getConfigurationSection("homes." + player.getUniqueId()).getKeys(false).size() : 0;

            if (currentHomes >= maxHomes) {
                player.sendMessage(lang.getString("sethome.limit-reached", "§cDu hast die maximale Anzahl an Homes erreicht!"));
                return true;
            }

            Location loc = player.getLocation();
            homes.set(path + ".world", loc.getWorld().getName());
            homes.set(path + ".x", loc.getX());
            homes.set(path + ".y", loc.getY());
            homes.set(path + ".z", loc.getZ());
            homes.set(path + ".yaw", loc.getYaw());
            homes.set(path + ".pitch", loc.getPitch());
            plugin.saveHomesConfig();

            player.sendMessage(lang.getString("sethome.success", "§aHome %name% wurde gesetzt!")
                .replace("%name%", homeName));
            return true;
        }

        if (commandName.equals("delhome")) {
            if (!player.hasPermission("survivalplus.homes.delete")) {
                player.sendMessage(lang.getString("no-permission", "§cDu hast keine Berechtigung für diesen Befehl!"));
                return true;
            }

            if (args.length != 1) {
                player.sendMessage(lang.getString("delhome.usage", "§cVerwendung: /delhome <name>"));
                return true;
            }

            String homeName = args[0].toLowerCase();
            String path = "homes." + player.getUniqueId() + "." + homeName;
            if (!homes.contains(path)) {
                player.sendMessage(lang.getString("delhome.not-found", "§cDieses Home existiert nicht!"));
                return true;
            }

            homes.set(path, null);
            plugin.saveHomesConfig();
            player.sendMessage(lang.getString("delhome.success", "§aHome %name% wurde gelöscht!")
                .replace("%name%", homeName));
            return true;
        }

        if (commandName.equals("homelist")) {
            if (!player.hasPermission("survivalplus.homes.list")) {
                player.sendMessage(lang.getString("no-permission", "§cDu hast keine Berechtigung für diesen Befehl!"));
                return true;
            }

            String path = "homes." + player.getUniqueId();
            if (!homes.contains(path) || homes.getConfigurationSection(path).getKeys(false).isEmpty()) {
                player.sendMessage(lang.getString("homelist.no-homes", "§cDu hast keine Homes gesetzt!"));
                return true;
            }

            Inventory gui = Bukkit.createInventory(null, 27, lang.getString("homelist.gui-title", "Deine Homes"));
            List<String> homeNames = new ArrayList<>(homes.getConfigurationSection(path).getKeys(false));
            
            for (int i = 0; i < Math.min(homeNames.size(), 27); i++) {
                String homeName = homeNames.get(i);
                String homePath = path + "." + homeName;
                ItemStack item = new ItemStack(Material.RED_BED);
                ItemMeta meta = item.getItemMeta();
                meta.setDisplayName("§a" + homeName);
                List<String> lore = new ArrayList<>();
                lore.add("§7Welt: " + homes.getString(homePath + ".world"));
                lore.add("§7X: " + String.format("%.2f", homes.getDouble(homePath + ".x")));
                lore.add("§7Y: " + String.format("%.2f", homes.getDouble(homePath + ".y")));
                lore.add("§7Z: " + String.format("%.2f", homes.getDouble(homePath + ".z")));
                meta.setLore(lore);
                item.setItemMeta(meta);
                gui.setItem(i, item);
            }

            player.openInventory(gui);
            return true;
        }

        return false;
    }
}