/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.entity.projectile;

import com.remains_cave.entity.ModEntities;
import com.remains_cave.item.ModItems;
import com.remains_cave.item.custom.TombBowItem;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.EntityHitResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import software.bernie.geckolib.animatable.GeoEntity;
import software.bernie.geckolib.animatable.instance.AnimatableInstanceCache;
import software.bernie.geckolib.animation.AnimatableManager;
import software.bernie.geckolib.animation.AnimationController;
import software.bernie.geckolib.animation.PlayState;
import software.bernie.geckolib.util.GeckoLibUtil;

public class CustomArrowEntity extends AbstractArrow implements GeoEntity {
    private final AnimatableInstanceCache cache = GeckoLibUtil.createInstanceCache(this);
    public int clientShakeTime; // 用于渲染

    // 基础构造（用于注册）
    public CustomArrowEntity(EntityType<? extends AbstractArrow> entityType, Level level) {
        super(entityType, level);
    }

    // 玩家/骷髅射手发射的构造（传入武器以应用附魔）
    public CustomArrowEntity(Level level, LivingEntity shooter, ItemStack pickupItemStack, @Nullable ItemStack firedFromWeapon, double damage) {
        super(ModEntities.TOMB_ARROW.get(), shooter, level, pickupItemStack, firedFromWeapon);
        this.setBaseDamage(damage);
    }

    // 从空中生成的构造（例如命令召唤）
    public CustomArrowEntity(Level level, double x, double y, double z, ItemStack pickupItemStack, @Nullable ItemStack firedFromWeapon, double damage) {
        super(ModEntities.TOMB_ARROW.get(), x, y, z, level, pickupItemStack, firedFromWeapon);
        this.setBaseDamage(damage);
    }

    @Override
    public void tick() {
        super.tick();
        if (level().isClientSide) {
            if (this.inGround) {
                if (clientShakeTime > 0) clientShakeTime--;
                else if (this.shakeTime > 0) clientShakeTime = this.shakeTime;
            } else {
                clientShakeTime = 0;
            }
        }
        // ========== 粒子效果已临时移除 ==========
        // if (!level().isClientSide && fromAuraArcher && !this.inGround) {
        //     if (level() instanceof ServerLevel serverLevel) {
        //         serverLevel.sendParticles(...);
        //     }
        // }
    }

    @Override
    protected void onHitEntity(EntityHitResult result) {
        Entity hitEntity = result.getEntity();
        // 队伍检查（保留，避免误伤友军）
        if (this.getOwner() instanceof Mob owner && hitEntity instanceof Mob targetMob) {
            if (owner.getTeam() != null && owner.getTeam().equals(targetMob.getTeam())) {
                return; // 同一队伍，不造成伤害
            }
        }
        // 调用父类处理基础弹射物伤害
        super.onHitEntity(result);

        // ========== 额外伤害和粒子效果已临时移除 ==========
        // if (fromAuraArcher && hitEntity instanceof LivingEntity livingTarget) {
        //     Entity owner = this.getOwner();
        //     if (owner instanceof LivingEntity livingOwner) {
        //         livingTarget.hurt(...);
        //         if (level() instanceof ServerLevel serverLevel) {
        //             serverLevel.sendParticles(...);
        //         }
        //     }
        // }
    }

    @Override
    protected @NotNull ItemStack getDefaultPickupItem() {
        return new ItemStack(ModItems.TOMB_ARROW.get());
    }

    @Override
    public void shoot(double x, double y, double z, float velocity, float inaccuracy) {
        float customVelocity = velocity;
        // 获取发射武器
        ItemStack weapon = this.getWeaponItem();
        if (weapon != null && !(weapon.getItem() instanceof TombBowItem)) {
            customVelocity *= 0.8f;
        }
        super.shoot(x, y, z, customVelocity, inaccuracy);
    }
    // 用于渲染的抖动振幅
    public float getShake(float partialTick) {
        if (shakeTime <= 0) return 0;
        float amplitude = Math.min(shakeTime, 10) * 0.2F;
        return amplitude * Mth.sin((this.tickCount + partialTick) * 0.5F);
    }

    public int getShakeTime() {
        return this.shakeTime;
    }

    public boolean isInGround() {
        return this.inGround;
    }

    private boolean fromAuraArcher = false;
    public void setFromAuraArcher(boolean fromAuraArcher) {
        this.fromAuraArcher = fromAuraArcher; // 变量保留，但当前未使用
    }

    @Override
    public void registerControllers(AnimatableManager.ControllerRegistrar controllers) {
        controllers.add(new AnimationController<>(this, "controller", 0, state -> PlayState.CONTINUE));
    }

    @Override
    public AnimatableInstanceCache getAnimatableInstanceCache() {
        return cache;
    }
}