package com.zivilon.cinder_loe.items.specials;

import com.zivilon.cinder_loe.CinderLoE_Config;
import com.zivilon.cinder_loe.LoECreativeTabs;
import com.zivilon.cinder_loe.entity.npc.orc.NorthernOrc;
import com.zivilon.cinder_loe.entity.npc.radagast.FangornAnimal;
import com.zivilon.cinder_loe.util.BlockPos;
import lotr.common.LOTRMod;
import lotr.common.entity.npc.*;
import lotr.common.fac.LOTRFaction;
import lotr.common.fac.LOTRFactionRelations;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;


public class Ulukai extends Item {
    private static final String ULUKAI_TAG = "UlukaiModifiers";
    LOTRFaction gundabad = LOTRFaction.valueOf(CinderLoE_Config.ulukai_faction);

    public Ulukai() {
        super();
        this.setCreativeTab(LoECreativeTabs.tabCharacterLoE);
    }

    public int getMaxItemUseDuration(ItemStack itemstack) {
        return 400;
    } //20 second usage before it spawns anything

    public EnumAction getItemUseAction(ItemStack itemstack) {
        return EnumAction.bow;
    }

    public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) {
        entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack));
        return itemstack;
    }

    @Override
    public ItemStack onEaten(ItemStack stack, World world, EntityPlayer player) {
        if (!world.isRemote) {
            if (isAreaCrowded(world, player)) {
                world.playSoundAtEntity(player, "lotr:item.puff", 1.0F, 2.0F);
            } else {
                for (int i = 0; i < 5; i++) {
                    BlockPos spawnPos = BlockPos.findSafeSpawnLocation(world, player);
                    if (spawnPos != null) {
                        spawnRandomGundabad(world, spawnPos);
                    }
                }

                world.playSoundAtEntity(player, "lotr:dwarf.kill", 2.0F,
                        (Item.itemRand.nextFloat() - Item.itemRand.nextFloat()) * 0.1F + 0.5F);
            }
        }

        return stack;
    }



    public boolean isAreaCrowded(World world, EntityPlayer player) {
        int radius = 30; // Check within 30 blocks
        int maxEntities = 50; // Maximum allowed nearby entities

        AxisAlignedBB checkArea = AxisAlignedBB.getBoundingBox(
                player.posX - radius, player.posY - radius, player.posZ - radius,
                player.posX + radius, player.posY + radius, player.posZ + radius
        );

        List<LOTREntityNPC> nearbyNpcs = world.getEntitiesWithinAABB(LOTREntityNPC.class, checkArea);
        int gundabadCount = 0;
        for (LOTREntityNPC npc : nearbyNpcs) {
            LOTRFaction faction = LOTRMod.getNPCFaction(npc);
            if (faction == gundabad) {
                gundabadCount++;
            }
        }
        return gundabadCount >= maxEntities;
    }


    @Override
    public void onUsingTick(ItemStack stack, EntityPlayer player, int count) {
        if (player.worldObj.isRemote) return;

        int ticksUsed = getMaxItemUseDuration(stack) - count;

        // Avoid triggering at tick 0
        if (ticksUsed > 0 && ticksUsed % 20 == 0) {
            applyAllyHealing(player.worldObj, player);
        }

        if (ticksUsed > 0 && ticksUsed % 200 == 0) {
            applyEnemyMaxHealthReduction(player.worldObj, player);
        }
    }

    public void spawnRandomGundabad(World world, BlockPos location) {
        Random rand = new Random();
        int choice = rand.nextInt(7); // 0 to 6

        EntityLiving entity;

        switch (choice) {
            case 0:
                entity = new LOTREntityGundabadOrc(world);
                break;
            case 1:
                entity = new LOTREntityGundabadOrcArcher(world);
                break;
            case 2:
                entity = new LOTREntityGundabadWarg(world);
                break;
            case 3:
                entity = new LOTREntityGundabadUruk(world);
                break;
            case 4:
                entity = new LOTREntityGundabadUrukArcher(world);
                break;
            case 5:
                entity = new LOTREntityGundabadBannerBearer(world);
                break;
            case 6:
                entity = new NorthernOrc(world);
                break;
            default:
                entity = new LOTREntityGundabadOrc(world);
                break;
        }

        entity.setPosition(location.x + 0.5, location.y, location.z + 0.5); // Center the entity on the block
        entity.onSpawnWithEgg((IEntityLivingData) null);
        world.spawnEntityInWorld(entity);
    }


    private void applyEnemyMaxHealthReduction(World world, EntityPlayer player) {
        LOTRFaction gundabad = LOTRFaction.GUNDABAD;

        List<EntityLivingBase> nearbyEntities = world.getEntitiesWithinAABB(
                EntityLivingBase.class, player.boundingBox.expand(10.0D, 10.0D, 10.0D));

        for (EntityLivingBase target : nearbyEntities) {
            if (target == player || target instanceof EntityPlayer) continue;

            if (target instanceof LOTREntityNPC) {
                LOTRFaction targetFaction = LOTRMod.getNPCFaction((LOTREntityNPC) target);
                if (targetFaction != null) {
                    LOTRFactionRelations.Relation relation = LOTRFactionRelations.getRelations(gundabad, targetFaction);

                    if (relation == LOTRFactionRelations.Relation.ENEMY || relation == LOTRFactionRelations.Relation.MORTAL_ENEMY) {
                        IAttributeInstance attribute = target.getEntityAttribute(SharedMonsterAttributes.maxHealth);
                        double currentMax = attribute.getAttributeValue();
                        double newMax = currentMax - 1.0D;

                        if (newMax >= 10.0D) {
                            AttributeModifier mod = new AttributeModifier(UUID.randomUUID(), "Ulukai Curse", -1.0D, 0);
                            attribute.applyModifier(mod);

                            // Save UUID + timestamp
                            NBTTagCompound data = target.getEntityData();
                            NBTTagList list = data.getTagList(ULUKAI_TAG, 10); // 10 = compound

                            NBTTagCompound entry = new NBTTagCompound();
                            entry.setString("UUID", mod.getID().toString());
                            entry.setLong("AppliedAt", player.ticksExisted); // or use world.getTotalWorldTime()

                            list.appendTag(entry);
                            data.setTag(ULUKAI_TAG, list);
                            System.out.println("Ulukai Curse applied to: " + target.getCommandSenderName() +
                                    " UUID=" + mod.getID() + " Tick=" + player.ticksExisted);

                            world.playSoundAtEntity(player, "lotr:wraith.marshWraith_shoot", 1F,1F);

                            for(int l = 0; l < 16; ++l) {
                                LOTRMod.proxy.spawnParticle("morgulPortal",
                                        target.posX, target.posY + 1.0D, target.posZ,
                                        0.0D, 0.02D, 0.0D);
                            }
                        }
                    }
                }
            }
        }
    }



    private void applyAllyHealing(World world, EntityPlayer player) {

        List<EntityLivingBase> nearbyEntities = world.getEntitiesWithinAABB(
                EntityLivingBase.class, player.boundingBox.expand(10.0D, 10.0D, 10.0D));

        List<EntityLivingBase> validTargets = new ArrayList<>();

        for (EntityLivingBase target : nearbyEntities) {
            if (target == player || target instanceof EntityPlayer) continue;

            if (target instanceof LOTREntityNPC) {
                LOTRFaction targetFaction = LOTRMod.getNPCFaction((LOTREntityNPC) target);
                if (targetFaction == gundabad && target.getHealth() < target.getMaxHealth()) {
                    validTargets.add(target);
                }
            }
        }

        // Heal a random wounded ally, if any exist
        if (!validTargets.isEmpty()) {
            EntityLivingBase toHeal = validTargets.get(world.rand.nextInt(validTargets.size()));
            toHeal.heal(1.0F); // 0.5 heart
            world.playSoundAtEntity(toHeal, "mob.zombie.unfect", 0.25F,1F);

            for(int l = 0; l < 8; ++l) {
                LOTRMod.proxy.spawnParticle("heart",
                        toHeal.posX, toHeal.posY + 1.0D, toHeal.posZ,
                        0.0D, 0.02D, 0.0D);
            }

        } else {
            // Fizzle
            world.playSoundAtEntity(player, "lotr:swan.hiss", 0.1F, 0.1F + world.rand.nextFloat() * 0.5F);
        }
    }


    public static void removeExpiredUlukaiModifiers(EntityLivingBase entity, long currentTick) {
        IAttributeInstance attr = entity.getEntityAttribute(SharedMonsterAttributes.maxHealth);
        NBTTagCompound data = entity.getEntityData();
        NBTTagList oldList = data.getTagList(ULUKAI_TAG, 10); // 10 = compound tag
        NBTTagList newList = new NBTTagList();

        for (int i = 0; i < oldList.tagCount(); i++) {
            NBTTagCompound entry = oldList.getCompoundTagAt(i);
            long applied = entry.getLong("AppliedAt");
            String uuidStr = entry.getString("UUID");

            if (currentTick - applied >= 72000L) { // 1 hour in ticks
                try {
                    UUID uuid = UUID.fromString(uuidStr);
                    AttributeModifier mod = attr.getModifier(uuid);
                    if (mod != null) {
                        attr.removeModifier(mod);
                        System.out.println("Ulukai Curse expired: " + entity.getCommandSenderName() +
                                " UUID=" + uuid + " Tick=" + currentTick);
                    }
                } catch (IllegalArgumentException e) {
                    // Invalid UUID format — skip
                }
            } else {
                newList.appendTag(entry); // Keep active ones
            }
        }

        data.setTag(ULUKAI_TAG, newList);
    }


}