package de.viper.survivalplus.fun;

import org.bukkit.Bukkit;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FunChallengeManager {

    private final List<FunChallenge> challenges = new ArrayList<>();
    private final Map<String, Integer> globalProgress = new HashMap<>(); // Fortschritt global für alle Spieler
    private final Map<Player, BossBar> playerBossBars = new HashMap<>();
    private BukkitRunnable bossBarTask;

    public void load(FileConfiguration config) {
        challenges.clear();
        globalProgress.clear();
        if (config.contains("funChallenges")) {
            for (Map<?, ?> entry : config.getMapList("funChallenges")) {
                FunChallenge fc = new FunChallenge();
                fc.setName((String) entry.get("name"));
                fc.setDescription((String) entry.get("description"));
                fc.setType((String) entry.get("type"));
                fc.setItem((String) entry.get("item"));
                fc.setAmount((Integer) entry.get("amount"));
                fc.setTimeLimitMinutes((Integer) entry.get("timeLimitMinutes"));
                fc.setActive(Boolean.parseBoolean(entry.get("active").toString()));
                fc.setReward((String) entry.get("reward"));
                challenges.add(fc);
                globalProgress.put(fc.getName(), 0);
            }
        }
        startBossBar(); // automatisch BossBar starten, falls eine Challenge aktiv ist
    }

    public List<FunChallenge> getChallenges() { return challenges; }

    public FunChallenge getActiveChallenge() {
        for (FunChallenge c : challenges) {
            if (c.isActive()) return c;
        }
        return null;
    }

    public int getGlobalProgress(String challengeName) {
        return globalProgress.getOrDefault(challengeName, 0);
    }

    public void setGlobalProgress(String challengeName, int amount) {
        globalProgress.put(challengeName, amount);
    }

    public void resetProgress(String challengeName) {
        globalProgress.put(challengeName, 0);
    }

    // ====================== BossBar-Funktion ======================

    public void startBossBar() {
        FunChallenge active = getActiveChallenge();
        if (active == null) return;

        stopBossBar(); // alte Bars entfernen, falls vorhanden

        int totalTime = active.getTimeLimitMinutes() * 60; // Gesamtzeit in Sekunden
        final int[] timeLeft = {totalTime};

        bossBarTask = new BukkitRunnable() {
            @Override
            public void run() {
                if (timeLeft[0] <= 0 || getActiveChallenge() == null) {
                    stopBossBar();
                    return;
                }

                double progress = (double) timeLeft[0] / totalTime;
                String formattedTime = formatTime(timeLeft[0]);

                for (Player player : Bukkit.getOnlinePlayers()) {
                    BossBar bar = playerBossBars.computeIfAbsent(player, p -> {
                        BossBar newBar = Bukkit.createBossBar(
                                active.getName() + " (" + formattedTime + ")",
                                BarColor.BLUE,
                                BarStyle.SOLID
                        );
                        newBar.addPlayer(p);
                        return newBar;
                    });

                    bar.setProgress(progress);
                    bar.setTitle(active.getName() + " (" + formattedTime + ")");
                }

                timeLeft[0]--;
            }
        };

        bossBarTask.runTaskTimer(Bukkit.getPluginManager().getPlugin("SurvivalPlus"), 0L, 20L);
    }

    public void stopBossBar() {
        if (bossBarTask != null) bossBarTask.cancel();
        for (BossBar bar : playerBossBars.values()) {
            bar.removeAll();
        }
        playerBossBars.clear();
    }

    private String formatTime(int seconds) {
        int minutes = seconds / 60;
        int sec = seconds % 60;
        return String.format("%02d:%02d", minutes, sec);
    }
}
