package com.r3944realms.leashedplayer;

import com.mojang.brigadier.CommandDispatcher;
import com.r3944realms.leashedplayer.content.blocks.ModBlocksRegister;
import com.r3944realms.leashedplayer.content.blocks.entity.ItemMemoryBlockEntity;
import com.r3944realms.leashedplayer.content.capabilities.ModCapabilities;
import com.r3944realms.leashedplayer.content.commands.LeashCommand;
import com.r3944realms.leashedplayer.content.commands.MotionCommand;
import com.r3944realms.leashedplayer.content.commands.TickCommand;
import com.r3944realms.leashedplayer.content.effects.ModPotionRegister;
import com.r3944realms.leashedplayer.content.items.ModItemRegister;
import com.r3944realms.leashedplayer.content.misc.LeadBreakItemBehavior;
import com.r3944realms.leashedplayer.modInterface.IEntityLeadExtension;
import com.r3944realms.leashedplayer.network.client.SyncLeashRopeLength;
import com.r3944realms.leashedplayer.utils.Util;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.Leashable;
import net.minecraft.world.entity.animal.Fox;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.alchemy.PotionBrewing;
import net.minecraft.world.item.alchemy.Potions;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.DispenserBlock;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent;
import net.neoforged.neoforge.common.Tags;
import net.neoforged.neoforge.event.AnvilUpdateEvent;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.brewing.RegisterBrewingRecipesEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.network.PacketDistributor;
import org.jetbrains.annotations.NotNull;


public class CommonEventHandler {
    @EventBusSubscriber(modid = LeashedPlayer.MOD_ID)
    public static class Game extends CommonEventHandler {
        @SubscribeEvent
        public static void onRegisterCommander(RegisterCommandsEvent event) {
            CommandDispatcher<CommandSourceStack> dispatcher = event.getDispatcher();
            LeashCommand.register(dispatcher);
            MotionCommand.register(dispatcher);
            TickCommand.register(dispatcher);
        }
        @SubscribeEvent
        public static void OnRegisterPotionBrewing(RegisterBrewingRecipesEvent event) {
            PotionBrewing.Builder builder = event.getBuilder();
            builder.addMix(Potions.WATER, Items.SLIME_BALL, ModPotionRegister.NO_LEASH);
        }

        @SubscribeEvent
        public static void OnLivingTickEvent(EntityTickEvent.Post event) {
            Entity entity = event.getEntity();
            Level level = entity.level();
            if (level.isClientSide()) {
                return;
            }
            if (entity instanceof Fox fox) {
                if (fox.getMainHandItem().is(ItemTags.ANVIL)) {
                    fox.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY);
                    Util.throwItemTowardsLook(fox, ModItemRegister.NEOFORGE.get(), 0.3f, 0.1f);
                    fox.playSound(SoundEvents.FOX_EAT);
                } else if (fox.getMainHandItem().is(ModItemRegister.NEOFORGE.get())) {
                    // 繞圈參數
                    float rotationSpeed = 10.0f;  // 每 tick 旋轉的角度
                    // 計算新的旋轉角度
                    fox.yBodyRot += rotationSpeed;     // 身體旋轉
                    fox.yHeadRot += rotationSpeed;     // 頭部旋轉
                    fox.yRotO += rotationSpeed;        // 當前旋轉角度
                    fox.yHeadRotO += rotationSpeed;    // 頭部的當前旋轉角度

                    // 確保旋轉角度不超出 360 度，重置為 0 以便持續旋轉
                    if (fox.yBodyRot >= 360) fox.yBodyRot -= 360;
                    if (fox.yHeadRot >= 360) fox.yHeadRot -= 360;

                }
            }
            if (entity instanceof Leashable leashable) {
                IEntityLeadExtension leadExtension = (IEntityLeadExtension) entity;
                if (leashable.isLeashed() && leadExtension.hasLeadLengthSync()) {
                    PacketDistributor.sendToAllPlayers(
                            new SyncLeashRopeLength(entity.getUUID().toString(), leadExtension.getLeashLength())
                    );
                    leadExtension.setLeadLengthSync(true);
                }
            }
        }
        @SubscribeEvent
        public static void onBlockInteract(PlayerInteractEvent.RightClickBlock event) {
            Level level = event.getLevel();
            BlockPos pos = event.getPos();
            Player player = event.getEntity();
            ItemStack heldItem = player.getItemInHand(event.getHand());
            if (level.getBlockEntity(pos) instanceof ItemMemoryBlockEntity be) {
                if(level.isClientSide) event.setCanceled(true);
                // 阻止默认操作（如打开GUI）
                event.setCanceled(true);
                if (!heldItem.isEmpty()) {
                    // 如果手持物品，记忆并复制
                    be.setMemorizedItem(heldItem);
                    copyAndDropItem(level, pos, heldItem.copy());
                } else {
                    // 如果空手，使用记忆的物品复制
                    ItemStack memorized = be.getMemorizedItem();
                    if (!memorized.isEmpty()) {
                        copyAndDropItem(level, pos, memorized.copy());
                    } else {
                        player.displayClientMessage(Component.literal("No item memorized!"), true);
                    }
                }

            }
        }
        // 复制并丢出物品
        private static void copyAndDropItem(Level level, BlockPos pos, ItemStack stack) {
            if (!level.isClientSide) {
                ItemEntity itemEntity = new ItemEntity(
                        level,
                        pos.getX() + 0.5,
                        pos.getY() + 1.0,
                        pos.getZ() + 0.5,
                        stack
                );
                level.addFreshEntity(itemEntity);
            }
        }
        @SubscribeEvent
        public static void OnAnvilUpdated(AnvilUpdateEvent event) {
            String name = event.getName();
            ItemStack left = event.getLeft();
            if (left.is(Items.ANVIL) && name != null && name.equals("NeoForge")) {
                event.setXpCost(1);
                event.setOutput(ModItemRegister.NEOFORGE.get().getDefaultInstance());
            } else if (left.is(ModItemRegister.NEOFORGE.get().asItem()) && name != null && name.equals("Forge")) {
                ItemStack instance = Items.ANVIL.getDefaultInstance();
                instance.set(DataComponents.CUSTOM_NAME, Component.literal("Forge").withStyle(ChatFormatting.BOLD).withStyle(ChatFormatting.AQUA));
                event.setOutput(instance);
                event.setXpCost(1);
            }
        }
    }
    @EventBusSubscriber(modid = LeashedPlayer.MOD_ID, bus = EventBusSubscriber.Bus.MOD)
    public static class Mod extends CommonEventHandler {
        @SubscribeEvent
        public static void onCommonSetup(FMLCommonSetupEvent event) {
            event.enqueueWork(() ->  {
                DispenserBlock.registerProjectileBehavior(ModItemRegister.LEASH_ROPE_ARROW.get());
                DispenserBlock.registerProjectileBehavior(ModItemRegister.TIPPED_LEASH_ROPE_ARROW.get());
                DispenserBlock.registerProjectileBehavior(ModItemRegister.SPECTRAL_LEASH_ROPE_ARROW.get());
                DispenserBlock.registerBehavior(ModItemRegister.AMETHYST_SHEARS.get(), new LeadBreakItemBehavior());
            });
        }

        @SubscribeEvent
        public static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
            event.registerBlock(
                    ModCapabilities.ITEM_MEMORY_COPY_BLOCK_CAP,
                    ((level, pos, state, blockEntity, context) -> new ItemStackHandler(1) {
                        @Override
                        public boolean isItemValid(int slot, @NotNull ItemStack stack) {
                            return true;
                        }

                        @Override
                        public @NotNull ItemStack insertItem(int slot, @NotNull ItemStack stack, boolean simulate) {
                            if (!simulate && !stack.isEmpty()) {
                                if (blockEntity instanceof ItemMemoryBlockEntity itemMemoryBlockEntity)
                                    itemMemoryBlockEntity.setMemorizedItem(stack);
                                else throw new IllegalStateException("BlockEntity must be an instance of ItemMemoryBlockEntity");
                            }
                            return stack; // 不实际存储物品，直接返回原物品
                        }
                    }),
                    ModBlocksRegister.TEST_BLOCK.get()
            );
        }
    }



}
