package com.playerblocklife;

import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 生命值系统 - 负责管理玩家生命值和状态效果
 * 
 * <p>根据玩家剩余生命方块数量计算生命值，并应用相应的状态效果：
 * <ul>
 *   <li>监控玩家剩余方块数量变化</li>
 *   <li>计算对应的生命值比例</li>
 *   <li>应用虚弱、缓慢、失明等负面效果</li>
 *   <li>处理玩家淘汰和复活逻辑</li>
 *   <li>提供生命值相关的音效和视觉反馈</li>
 * </ul>
 * 
 * <p>生命值计算公式：
 * <pre>
 * 5个方块 → 20点生命值（满血）
 * 4个方块 → 16点生命值
 * 3个方块 → 12点生命值
 * 2个方块 → 8点生命值
 * 1个方块 → 4点生命值
 * 0个方块 → 0点生命值（淘汰）
 * </pre>
 * 
 * @author xiaobai
 * @version 2.2.0
 * @since 1.0.0
 */
public class LifeSystem {
    private final PlayerBlockLife plugin;
    private final Map<UUID, Integer> playerHealth = new HashMap<>();
    private final Map<UUID, Long> lastDamageTime = new HashMap<>();

    public LifeSystem(PlayerBlockLife plugin) {
        this.plugin = plugin;
    }

    public void checkAllPlayers() {
        // 只在游戏进行中时检查玩家生命值，等待和旁观状态的玩家不检查
        if (plugin.getGameStateManager().getCurrentState() == GameStateManager.GameState.STARTED) {
            for (Player player : Bukkit.getOnlinePlayers()) {
                // 只检查生存模式的玩家（非旁观者）
                if (player.getGameMode() == GameMode.SURVIVAL) {
                    checkPlayerHealth(player);
                }
            }
        }
    }

    public void checkPlayerHealth(Player player) {
        UUID playerId = player.getUniqueId();
        int remainingBlocks = plugin.getBlockManager().getRemainingBlocks(playerId);

        if (remainingBlocks == 0 && !playerHealth.containsKey(playerId)) {
            playerHealth.put(playerId, 20);
            return;
        }

        int newHealth = calculateHealthFromBlocks(remainingBlocks);
        Integer currentHealth = playerHealth.get(playerId);

        if (currentHealth == null) {
            playerHealth.put(playerId, newHealth);
            return;
        }

        if (currentHealth != newHealth) {
            playerHealth.put(playerId, newHealth);

            if (newHealth < currentHealth) {
                player.sendMessage("§c你的生命值减少了！当前: §4" + newHealth + " ❤");
                player.playSound(player.getLocation(),
                        org.bukkit.Sound.ENTITY_PLAYER_HURT, 1.0f, 1.0f);
                lastDamageTime.put(playerId, System.currentTimeMillis());
            } else if (newHealth > currentHealth) {
                player.sendMessage("§a你的生命值恢复了！当前: §2" + newHealth + " ❤");
                player.playSound(player.getLocation(),
                        org.bukkit.Sound.ENTITY_PLAYER_LEVELUP, 0.5f, 1.5f);
            }

            if (newHealth <= 5) {
                player.sendTitle("§4⚠ 警告！", "§c生命值过低！", 10, 40, 10);
                player.playSound(player.getLocation(),
                        org.bukkit.Sound.BLOCK_NOTE_BLOCK_BELL, 1.0f, 0.5f);
            }

            if (remainingBlocks == 0) {
                handlePlayerDeath(playerId);
            }
        }

        applyStatusEffects(player, remainingBlocks);
    }

    private int calculateHealthFromBlocks(int remainingBlocks) {
        if (remainingBlocks >= 5) return 20;
        if (remainingBlocks == 4) return 16;
        if (remainingBlocks == 3) return 12;
        if (remainingBlocks == 2) return 8;
        if (remainingBlocks == 1) return 4;
        return 0;
    }

    private void applyStatusEffects(Player player, int remainingBlocks) {
        if (remainingBlocks <= 2) {
            player.addPotionEffect(new PotionEffect(
                    PotionEffectType.SLOW, 100, 1, true, true));

            if (remainingBlocks == 1) {
                player.addPotionEffect(new PotionEffect(
                        PotionEffectType.WEAKNESS, 100, 0, true, true));
                player.addPotionEffect(new PotionEffect(
                        PotionEffectType.BLINDNESS, 100, 0, true, true));
            }
        } else {
            player.removePotionEffect(PotionEffectType.SLOW);
            player.removePotionEffect(PotionEffectType.WEAKNESS);
            player.removePotionEffect(PotionEffectType.BLINDNESS);
        }
    }

    public void handlePlayerDeath(UUID playerId) {
        Player player = Bukkit.getPlayer(playerId);
        if (player == null || !player.isOnline()) {
            return;
        }

        player.setHealth(0);
        player.sendTitle("§4☠ 你死了！", "§c所有生命方块已被挖光", 20, 100, 20);

        for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
            onlinePlayer.sendMessage("§4☠ 玩家 " + player.getName() + " 的生命方块已被全部挖光，惨遭淘汰！");
            onlinePlayer.playSound(onlinePlayer.getLocation(),
                    org.bukkit.Sound.ENTITY_WITHER_DEATH, 0.7f, 0.8f);
        }

        plugin.getBlockManager().clearPlayerBlocks(playerId);
        playerHealth.remove(playerId);

        Bukkit.getScheduler().runTaskLater(plugin, () -> {
            if (player.isOnline()) {
                player.setGameMode(GameMode.SPECTATOR);
                player.sendMessage("§e你已被淘汰，可以观察其他玩家。");
                player.sendMessage("§7等待下一轮游戏开始...");
            }
        }, 100L);
    }

    public Integer getPlayerHealth(UUID playerId) {
        return playerHealth.get(playerId);
    }

    public void setPlayerHealth(UUID playerId, int health) {
        playerHealth.put(playerId, health);
    }

    public boolean isPlayerAlive(UUID playerId) {
        Integer health = playerHealth.get(playerId);
        return health != null && health > 0;
    }

    public void revivePlayer(Player player) {
        UUID playerId = player.getUniqueId();
        playerHealth.put(playerId, 20);
        player.setGameMode(GameMode.SURVIVAL);
        player.setHealth(20.0);
        player.setFoodLevel(20);
        player.setSaturation(5.0f);

        player.removePotionEffect(PotionEffectType.SLOW);
        player.removePotionEffect(PotionEffectType.WEAKNESS);
        player.removePotionEffect(PotionEffectType.BLINDNESS);

        player.sendMessage("§a你已复活！生命值已恢复。");
        player.playSound(player.getLocation(),
                org.bukkit.Sound.ENTITY_PLAYER_LEVELUP, 1.0f, 1.0f);
    }
}