package com.playerblocklife;

import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
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.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;

import java.util.UUID;

public class BlockBreakListener implements Listener {
    private final PlayerBlockLife plugin;

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

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onBlockBreak(BlockBreakEvent event) {
        Player breaker = event.getPlayer();
        Block block = event.getBlock();
        Location location = block.getLocation();

        if (block.getType() != Material.PLAYER_HEAD &&
                block.getType() != Material.PLAYER_WALL_HEAD) {
            return;
        }

        UUID ownerId = plugin.getBlockManager().getBlockOwner(location);
        if (ownerId == null) {
            return;
        }

        if (ownerId.equals(breaker.getUniqueId())) {
            if (breaker.getGameMode() != GameMode.CREATIVE) {
                breaker.sendMessage("§c你不能挖掘自己的生命方块！");
                event.setCancelled(true);
            }
            return;
        }

        if (plugin.getBlockManager().removeBlock(location, breaker)) {
            int remaining = plugin.getBlockManager().getRemainingBlocks(ownerId);

            if (remaining <= 0) {
                plugin.getLifeSystem().handlePlayerDeath(ownerId);
            }

            breaker.sendMessage("§a✓ 成功破坏一个生命方块！");
            breaker.sendMessage("§7剩余方块: §e" + remaining);

            if (remaining == 1) {
                breaker.sendMessage("§6⚡ 对方只剩最后1个生命方块了！");
                breaker.playSound(breaker.getLocation(),
                        org.bukkit.Sound.ENTITY_PLAYER_LEVELUP, 1.0f, 1.5f);
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onBlockPlace(BlockPlaceEvent event) {
        Player player = event.getPlayer();
        Block block = event.getBlock();

        if (block.getType() == Material.PLAYER_HEAD ||
                block.getType() == Material.PLAYER_WALL_HEAD) {

            UUID ownerId = plugin.getBlockManager().getBlockOwner(block.getLocation());
            if (ownerId != null && !ownerId.equals(player.getUniqueId())) {
                player.sendMessage("§c你不能在这里放置方块，这是别人的生命方块区域！");
                event.setCancelled(true);
            }
        }
    }
}