package com.r3944realms.leashedplayer;

import com.mojang.brigadier.CommandDispatcher;
import com.r3944realms.leashedplayer.content.commands.ChatCommand;
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.ModEffectRegister;
import com.r3944realms.leashedplayer.content.effects.ModPotionRegister;
import com.r3944realms.leashedplayer.content.entities.LeashRopeArrow;
import com.r3944realms.leashedplayer.content.entities.LittlePlayer;
import com.r3944realms.leashedplayer.content.entities.ModEntityRegister;
import com.r3944realms.leashedplayer.content.items.ModItemRegister;
import com.r3944realms.leashedplayer.content.items.repcipe.ModRecipeSerializer;
import com.r3944realms.leashedplayer.content.items.repcipe.TippedLeashRopeArrowRecipe;
import com.r3944realms.leashedplayer.content.misc.LeadBreakItemBehavior;
import com.r3944realms.leashedplayer.modInterface.PlayerLeashable;
import com.r3944realms.leashedplayer.utils.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.Leashable;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.animal.Fox;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.Item;
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.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.SimpleCraftingRecipeSerializer;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.brewing.RegisterBrewingRecipesEvent;
import net.neoforged.neoforge.event.entity.EntityAttributeCreationEvent;
import net.neoforged.neoforge.event.tick.EntityTickEvent;
import net.neoforged.neoforge.registries.RegisterEvent;


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);
            ChatCommand.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 LivingEntity living) {
                MobEffectInstance effect = living.getEffect(ModEffectRegister.NO_LEASH_EFFECT);
                if (effect != null && effect.getDuration() != 0) {
                    if (entity instanceof PlayerLeashable player) {
                        if (player.getLeashHolder() != null) {
                            if (player.getLeashHolder() instanceof LeashRopeArrow arrow)
                                arrow.setOwner(null);
                            player.dropLeash(true, !(player.getLeashHolder() instanceof LeashRopeArrow));
                        }
                    } else if (entity instanceof Leashable leashable) {
                        if (leashable.getLeashHolder() != null) {
                            if (leashable.getLeashHolder() instanceof LeashRopeArrow arrow)
                                arrow.setOwner(null);
                            leashable.dropLeash(true, !(leashable.getLeashHolder() instanceof LeashRopeArrow));
                        }
                    }
                }
                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(fox.getEatingSound(ItemStack.EMPTY));
                    } 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;

                    }
                }
            }
        }

        @EventBusSubscriber(modid = LeashedPlayer.MOD_ID, bus = EventBusSubscriber.Bus.MOD)
        public static class Mod extends CommonEventHandler {
            @SubscribeEvent
            public static void onCommonSetup(FMLCommonSetupEvent event) {
                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 onEntityAttributeEvent(EntityAttributeCreationEvent event) {
                event.put(ModEntityRegister.KID.get(), LittlePlayer.createAttributes().build());
            }

            @SubscribeEvent
            public static void onRegisterEvent(RegisterEvent event) {
                if (event.getRegistry() == BuiltInRegistries.RECIPE_SERIALIZER) {
                    ModRecipeSerializer.TIPPED_LEASH_ROPE_ARROW_A_RECIPE =
                            RecipeSerializer.register(
                                    "tipped_leash_rope_arrow_a_recipe",
                                    new SimpleCraftingRecipeSerializer<>(TippedLeashRopeArrowRecipe.TippedLeashRopeArrowARecipe::new)
                            );
                    ModRecipeSerializer.TIPPED_LEASH_ROPE_ARROW_B_RECIPE =
                            RecipeSerializer.register("tipped_leash_rope_arrow_b_recipe",
                                    new SimpleCraftingRecipeSerializer<>(TippedLeashRopeArrowRecipe.TippedLeashRopeArrowBRecipe::new)
                            );
                }
            }

        }

    }

}
