package de.viper.survivalplus.listeners;

import de.viper.survivalplus.fun.FunChallenge;
import de.viper.survivalplus.fun.FunChallengeManager;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.FurnaceExtractEvent;
import org.bukkit.inventory.ItemStack;

public class ChallengeSmeltListener implements Listener {

    private final FunChallengeManager challengeManager;

    public ChallengeSmeltListener(FunChallengeManager challengeManager) {
        this.challengeManager = challengeManager;
    }

    @EventHandler
    public void onFurnaceExtract(FurnaceExtractEvent event) {
        Player player = (Player) event.getPlayer();

        FunChallenge active = challengeManager.getActiveChallenge();
        if (active == null) return;

        if (!"COLLECT".equalsIgnoreCase(active.getType())) return;

        String requiredItem = active.getItem();
        int requiredAmount = active.getAmount();

        String smeltedItem = event.getItemType().name();
        if (!smeltedItem.equalsIgnoreCase(requiredItem)) return;

        int current = challengeManager.getGlobalProgress(active.getName());
        current += event.getItemAmount();
        challengeManager.setGlobalProgress(active.getName(), current);

        if (current >= requiredAmount) {
            player.getServer().broadcastMessage("§aChallenge \"" + active.getName() + "\" geschafft!");
            giveReward(player, active.getReward());
            active.setActive(false);
            challengeManager.resetProgress(active.getName());
        } else {
            player.sendMessage("§eFortschritt: " + current + "/" + requiredAmount + " " + requiredItem);
        }
    }

    private void giveReward(Player player, String reward) {
        if (reward == null || reward.isEmpty()) return;

        String[] parts = reward.split(",");
        if (parts.length != 2) return;

        String itemName = parts[0];
        int amount;
        try {
            amount = Integer.parseInt(parts[1]);
        } catch (NumberFormatException e) {
            return;
        }

        Material material = Material.matchMaterial(itemName);
        if (material == null) return;

        ItemStack rewardItem = new ItemStack(material, amount);
        player.getInventory().addItem(rewardItem);
        player.sendMessage("§aDu hast deine Belohnung erhalten: " + amount + "x " + itemName);
    }
}
