package de.viper.survivalplus.listeners;

import de.viper.survivalplus.SurvivalPlus;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;

public class SignShopListener implements Listener {
    private final SurvivalPlus plugin;
    private Economy economy;

    public SignShopListener(SurvivalPlus plugin) {
        this.plugin = plugin;
        try {
            if (plugin.getServer().getPluginManager().isPluginEnabled("Vault")) {
                RegisteredServiceProvider<Economy> rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class);
                if (rsp != null) {
                    this.economy = rsp.getProvider();
                    plugin.getLogger().info("Vault Economy für Sign Shops gefunden.");
                } else {
                    plugin.getLogger().warning("Vault Economy Service nicht gefunden!");
                }
            } else {
                plugin.getLogger().warning("Vault Plugin nicht installiert! Sign Shops funktionieren nicht.");
            }
        } catch (Exception e) {
            plugin.getLogger().warning("Fehler beim Laden der Vault API.");
        }
    }

    // --- Schild erstellung ---
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onSignChange(SignChangeEvent event) {
        String line0Raw = event.getLine(0);
        if (!line0Raw.equalsIgnoreCase("[buy]") && !line0Raw.equalsIgnoreCase("[sell]")) {
            return;
        }
        
        Player player = event.getPlayer();
        if (!player.hasPermission("survivalplus.shop.create")) {
            player.sendMessage(ChatColor.RED + "Keine Berechtigung, Shops zu erstellen.");
            return;
        }

        String line2 = event.getLine(1);
        String line3 = event.getLine(2);

        String[] parts = line2.split(" ");
        if (parts.length < 2) {
            player.sendMessage(ChatColor.RED + "Format in Zeile 2 falsch! Beispiel: 64 Diamond");
            event.setCancelled(true);
            return;
        }
        
        try {
            Integer.parseInt(parts[0]);
            if (Material.matchMaterial(parts[1]) == null) {
                 player.sendMessage(ChatColor.RED + "Das Item '" + parts[1] + "' existiert nicht.");
                 event.setCancelled(true);
                 return;
            }
            Double.parseDouble(line3);
        } catch (Exception e) {
            player.sendMessage(ChatColor.RED + "Fehler im Format! Benutze: [Buy] \n 64 Diamond \n 500");
            event.setCancelled(true);
            return;
        }

        // --- NEU: Schild farbig machen ---
        if (line0Raw.equalsIgnoreCase("[buy]")) {
            event.setLine(0, ChatColor.GREEN + "[BUY]");
            event.setLine(1, ChatColor.WHITE + parts[0] + " " + ChatColor.AQUA + parts[1]);
            event.setLine(2, ChatColor.GOLD + line3 + " Coins");
        } else if (line0Raw.equalsIgnoreCase("[sell]")) {
            event.setLine(0, ChatColor.RED + "[SELL]");
            event.setLine(1, ChatColor.WHITE + parts[0] + " " + ChatColor.AQUA + parts[1]);
            event.setLine(2, ChatColor.GOLD + line3 + " Coins");
        }
        
        if (event.getLine(3) != null && !event.getLine(3).isEmpty()) {
             event.setLine(3, ChatColor.GRAY + event.getLine(3));
        }
    }

    // --- Interaktion ---
    @EventHandler(priority = EventPriority.HIGHEST)
    public void onPlayerInteract(PlayerInteractEvent event) {
        Block block = event.getClickedBlock();
        if (block == null || !(block.getState() instanceof Sign)) {
            return;
        }

        Sign sign = (Sign) block.getState();
        String line0 = ChatColor.stripColor(sign.getLine(0));

        if (!line0.equalsIgnoreCase("[buy]") && !line0.equalsIgnoreCase("[sell]")) {
            return;
        }

        if (economy == null) {
            event.getPlayer().sendMessage(ChatColor.RED + "Shop System offline (Vault fehlt).");
            return;
        }

        // --- FEATURE: SHIFT+KLICK LOGIK (LÖSCHEN) ---
        if (event.getPlayer().isSneaking()) {
            Player player = event.getPlayer();
            if (!player.hasPermission("survivalplus.shop.create")) {
                player.sendMessage(ChatColor.RED + "Keine Berechtigung, Shops zu entfernen.");
                event.setCancelled(true);
                return;
            }
            block.breakNaturally();
            player.sendMessage(ChatColor.GREEN + "Shop entfernt.");
            event.setCancelled(true);
            return;
        }

        // --- ROUTING ---
        if (line0.equalsIgnoreCase("[buy]")) {
            handleBuy(event, sign);
        } else if (line0.equalsIgnoreCase("[sell]")) {
            handleSell(event, sign);
        }
    }

    // --- KAUFS LOGIK (ROBUST) ---
    private void handleBuy(PlayerInteractEvent event, Sign sign) {
        event.setCancelled(true); // Interaktion stoppen

        Player player = event.getPlayer();
        String line1Raw = ChatColor.stripColor(sign.getLine(1)); // "64 Diamond"
        String line2Raw = ChatColor.stripColor(sign.getLine(2)); // "500" oder "500 Coins"

        // 1. Validierung: Zeilen leer?
        if (line1Raw == null || line1Raw.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Zeile 1 des Schildes ist leer! (Format: 64 Diamond)");
            return;
        }
        if (line2Raw == null || line2Raw.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Preiszeile ist leer! (Format: 500)");
            return;
        }

        // 2. Parsing: Zeile 1 "64 Diamond"
        String[] partsRaw = line1Raw.split(" ");
        if (partsRaw.length < 2) {
            player.sendMessage(ChatColor.RED + "Falsches Format! Benutze: [Buy] \n 64 Diamond");
            return;
        }

        String amountStr = partsRaw[0].trim(); // "64"
        String itemNameStr = partsRaw[1].trim(); // "Diamond"

        if (amountStr.isEmpty() || itemNameStr.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Format Fehler!");
            return;
        }

        int amount;
        Material material;
        try {
            amount = Integer.parseInt(amountStr);
            material = Material.matchMaterial(itemNameStr);
        } catch (NumberFormatException e) {
            player.sendMessage(ChatColor.RED + "Angebot '" + amountStr + "' ist keine Zahl! (Beispiel: 64)");
            return;
        }

        if (material == null) {
            player.sendMessage(ChatColor.RED + "Item '" + itemNameStr + "' existiert nicht!");
            return;
        }

        // 3. Parsing: Zeile 2 "500 Coins" (Hier passierte der Fehler!)
        String[] priceParts = line2Raw.split(" ");
        if (priceParts.length == 0) {
             player.sendMessage(ChatColor.RED + "Preiszeile ist leer! (Beispiel: 500)");
             return;
        }

        String priceStr = priceParts[0].trim();
        if (priceStr.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Kein Preis gefunden! (Beispiel: 500)");
            return;
        }

        double price;
        try {
            price = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            player.sendMessage(ChatColor.RED + "Preis '" + priceStr + "' ist keine Zahl! (Beispiel: 500)");
            return;
        } catch (ArrayIndexOutOfBoundsException e) {
            player.sendMessage(ChatColor.RED + "Fehlerhafter Preis! (Beispiel: 500)");
            return;
        }

        if (amount <= 0 || price < 0) {
            player.sendMessage(ChatColor.RED + "Negative Werte sind nicht erlaubt.");
            return;
        }

        // 4. Transaktion
        try {
            ItemStack item = new ItemStack(material, amount);

            if (economy.getBalance(player) >= price) {
                EconomyResponse response = economy.withdrawPlayer(player, price);
                if (response.transactionSuccess()) {
                    player.getInventory().addItem(item);
                    player.sendMessage(ChatColor.GREEN + "Du hast " + amount + " " + material.name().toLowerCase() + " für " + price + " gekauft!");
                } else {
                    player.sendMessage(ChatColor.RED + "Fehler bei der Transaktion.");
                }
            } else {
                player.sendMessage(ChatColor.RED + "Du hast nicht genug Geld! Du brauchst " + price + ".");
            }
        } catch (Exception e) {
            player.sendMessage(ChatColor.RED + "Ein Fehler ist beim Lesen des Shops aufgetreten.");
            // Loggen für Debugging, falls Vault spinnt
            e.printStackTrace();
        }
    }

    // --- VERKAUFS LOGIK ---
    private void handleSell(PlayerInteractEvent event, Sign sign) {
        event.setCancelled(true);

        Player player = event.getPlayer();
        String line1Raw = ChatColor.stripColor(sign.getLine(1));
        String line2Raw = ChatColor.stripColor(sign.getLine(2));

        if (line1Raw == null || line1Raw.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Zeile 1 ist leer!");
            return;
        }
        if (line2Raw == null || line2Raw.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Zeile 2 ist leer!");
            return;
        }

        String[] partsRaw = line1Raw.split(" ");
        if (partsRaw.length < 2) {
            player.sendMessage(ChatColor.RED + "Format falsch! Benutze: [Sell] \n 64 Diamond");
            return;
        }

        String amountStr = partsRaw[0].trim();
        String itemNameStr = partsRaw[1].trim();

        int amount;
        Material material;
        try {
            amount = Integer.parseInt(amountStr);
            material = Material.matchMaterial(itemNameStr);
        } catch (NumberFormatException e) {
            player.sendMessage(ChatColor.RED + "Menge ist keine Zahl!");
            return;
        }

        if (material == null) {
            player.sendMessage(ChatColor.RED + "Item existiert nicht!");
            return;
        }

        // Preis Parsing (wie im Kauf, nur sicherer)
        String[] priceParts = line2Raw.split(" ");
        if (priceParts.length == 0) {
            player.sendMessage(ChatColor.RED + "Preiszeile ist leer!");
            return;
        }
        String priceStr = priceParts[0].trim();
        if (priceStr.isEmpty()) {
            player.sendMessage(ChatColor.RED + "Kein Preis!");
            return;
        }

        double price;
        try {
            price = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            player.sendMessage(ChatColor.RED + "Preis '" + priceStr + "' ist keine Zahl!");
            return;
        }

        if (amount <= 0 || price < 0) {
            player.sendMessage(ChatColor.RED + "Negativer Wert!");
            return;
        }

        ItemStack tempItem = new ItemStack(material, amount);
        int hasAmount = 0;
        
        for (ItemStack item : player.getInventory().getStorageContents()) {
            if (item != null && item.isSimilar(tempItem)) {
                hasAmount += item.getAmount();
            }
        }

        if (hasAmount < amount) {
            player.sendMessage(ChatColor.RED + "Du hast nicht genug Items!");
            return;
        }

        // Verkauf durchführen
        player.getInventory().removeItem(new ItemStack(material, amount));
        economy.depositPlayer(player, price);
        player.updateInventory();

        player.sendMessage(ChatColor.GREEN + "Du hast " + amount + " " + material.name().toLowerCase() + " für " + price + " Coins verkauft!");
    }
}