package de.viper.survivalplus.listeners;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;

public class RepairSignListener implements Listener {

    private final FileConfiguration config;
    private final FileConfiguration lang;

    public RepairSignListener(FileConfiguration config, FileConfiguration lang) {
        this.config = config;
        this.lang = lang;
    }

    private String msg(String key) {
        String raw = lang.getString(key, "&c[Missing lang key: " + key + "]");
        return ChatColor.translateAlternateColorCodes('&', raw);
    }

    private String msg(String key, String... replacements) {
        String raw = lang.getString(key, "&c[Missing lang key: " + key + "]");
        for (int i = 0; i < replacements.length - 1; i += 2) {
            raw = raw.replace(replacements[i], replacements[i + 1]);
        }
        return ChatColor.translateAlternateColorCodes('&', raw);
    }

    @EventHandler
    public void onSignCreate(SignChangeEvent event) {
        Player player = event.getPlayer();
        if (event.getLine(0) != null && event.getLine(0).equalsIgnoreCase("[Repair]")) {
            if (player.hasPermission("survivalplus.createrepairsign")) {
                event.setLine(0, ChatColor.DARK_GREEN + "[Repair]");
                event.setLine(1, ChatColor.GRAY + config.getString("repair.currency"));
                event.setLine(2, ChatColor.GOLD + String.valueOf(config.getInt("repair.price")));
                player.sendMessage(msg("repair.sign_created"));
            } else {
                player.sendMessage(msg("repair.no_permission_create"));
                event.setCancelled(true);
            }
        }
    }

    // Verhindert Bearbeitung bestehender Repair-Schilder
    @EventHandler
    public void onSignEdit(SignChangeEvent event) {
        Block block = event.getBlock();
        if (block.getState() instanceof Sign) {
            Sign sign = (Sign) block.getState();
            String line0 = ChatColor.stripColor(sign.getLine(0));
            if (line0.equalsIgnoreCase("[Repair]") && !event.getPlayer().isOp()) {
                event.getPlayer().sendMessage(msg("repair.no_edit"));
                event.setCancelled(true);
            }
        }
    }

    // Nur OP darf Schild abbauen
    @EventHandler
    public void onSignBreak(BlockBreakEvent event) {
        if (event.getBlock().getState() instanceof Sign) {
            Sign sign = (Sign) event.getBlock().getState();
            String line0 = ChatColor.stripColor(sign.getLine(0));
            if (line0.equalsIgnoreCase("[Repair]") && !event.getPlayer().isOp()) {
                event.getPlayer().sendMessage(msg("repair.no_break"));
                event.setCancelled(true);
            }
        }
    }

    @EventHandler
    public void onSignClick(PlayerInteractEvent event) {
        if (event.getClickedBlock() == null) return;
        if (!(event.getClickedBlock().getState() instanceof Sign)) return;

        Sign sign = (Sign) event.getClickedBlock().getState();
        String line0 = ChatColor.stripColor(sign.getLine(0));
        if (!line0.equalsIgnoreCase("[Repair]")) return;

        Player player = event.getPlayer();
        ItemStack item = player.getInventory().getItemInMainHand();

        if (!(item.getItemMeta() instanceof Damageable)) {
            player.sendMessage(msg("repair.not_repairable"));
            return;
        }

        Damageable meta = (Damageable) item.getItemMeta();
        int currentDamage = meta.getDamage();

        // Prüfen ob bereits voll repariert
        if (currentDamage <= 0) {
            player.sendMessage(msg("repair.already_fully_repaired"));
            return;
        }

        String currencyType = config.getString("repair.currency", "GOLD_INGOT");
        int price = config.getInt("repair.price", 5);

        Material currencyMaterial;
        try {
            currencyMaterial = Material.valueOf(currencyType.toUpperCase());
        } catch (IllegalArgumentException e) {
            player.sendMessage(msg("repair.invalid_currency"));
            return;
        }

        // Prüfung ob Währung erlaubt ist
        if (!isAllowedCurrency(currencyMaterial)) {
            player.sendMessage(msg("repair.invalid_currency"));
            return;
        }

        if (!player.getInventory().containsAtLeast(new ItemStack(currencyMaterial), price)) {
            player.sendMessage(msg("repair.not_enough_currency", "%currency%", currencyType));
            return;
        }

        // Zahlung abbuchen
        player.getInventory().removeItem(new ItemStack(currencyMaterial, price));

        // Item reparieren
        meta.setDamage(0);
        item.setItemMeta(meta);

        player.sendMessage(msg("repair.success",
                "%price%", String.valueOf(price),
                "%currency%", currencyType));
    }

    private boolean isAllowedCurrency(Material mat) {
        switch (mat) {
            case GOLD_INGOT:
            case IRON_INGOT:
            case DIAMOND:
            case NETHERITE_INGOT:
            case COPPER_INGOT:
            case EMERALD:
            case LAPIS_LAZULI:
                return true;
            default:
                return false;
        }
    }
}
