package top.r3944realms.eroticdungeongame.content.entity;


import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
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.level.Level;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.network.NetworkHooks;
import org.jetbrains.annotations.NotNull;

/**
 * 座椅实体 - 用于处理玩家坐在束缚设备上的逻辑
 */
public class SeatEntity extends Entity {

    private BlockPos linkedBlockPos;
    private boolean isRemoving;

    public SeatEntity(EntityType<? extends SeatEntity> entityType, Level level) {
        super(entityType, level);
        this.isRemoving = false;
    }

    @Override
    public void positionRider(@NotNull Entity passenger, @NotNull MoveFunction callback) {
        super.positionRider(passenger);

        // 客户端不需要处理
        if (this.level().isClientSide()) {
            return;
        }

        updateLinkedBlock();
    }

    @Override
    public void removePassenger(@NotNull Entity passenger) {
        super.removePassenger(passenger);

        // 只在服务端处理，且确保没有其他乘客
        if (this.level().isClientSide() || !getPassengers().isEmpty()) {
            return;
        }

        updateLinkedBlock();

        // 如果是生物实体，设置其位置
        if (passenger instanceof LivingEntity livingEntity) {
            Vec3 dismountPosition = getDismountLocationForPassenger(livingEntity);
            passenger.setPos(dismountPosition.x(), dismountPosition.y(), dismountPosition.z());
        }
    }

    @Override
    public void onPassengerTurned(@NotNull Entity passenger) {
        super.onPassengerTurned(passenger);

//        // 如果不是笼子类型的座椅，限制乘客的旋转 (未做)
//        if (!SeatType.CAGE.equals(FurnitureHelper.get(this)) &&
//                passenger instanceof LivingEntity livingEntity) {
//
//            limitPassengerRotation(livingEntity);
//        }
    }

    /**
     * 限制乘客的旋转角度
     */
    private void limitPassengerRotation(LivingEntity passenger) {
        passenger.setYBodyRot(getYRot());

        float deltaYaw = Mth.wrapDegrees(passenger.getYRot() - getYRot());
        float clampedYaw = Mth.clamp(deltaYaw, -90.0f, 90.0f);

        passenger.yRotO += clampedYaw - deltaYaw;
        passenger.setYRot(passenger.getYRot() + clampedYaw - deltaYaw);
        passenger.setYHeadRot(passenger.getYRot());
    }

    @Override
    public boolean shouldRiderSit() {
        return false;
    }

    @Override
    public boolean isPickable() {
        return false;
    }

    /**
     * 更新链接的方块状态
     */
    private void updateLinkedBlock() {
        if (this.linkedBlockPos != null) {
            this.level().blockUpdated(this.linkedBlockPos,
                    this.level().getBlockState(this.linkedBlockPos).getBlock());
        }
    }

    @Override
    @NotNull
    public Vec3 getDismountLocationForPassenger(@NotNull LivingEntity passenger) {
        BlockPos blockPos = getLinkedBlockPos().above();

        // 在周围寻找合适的下马位置
        for (int x = -1; x <= 1; x++) {
            for (int z = -1; z <= 1; z++) {
                if (x != 0 || z != 0) {
                    BlockPos checkPos = blockPos.offset(x, 0, z);
                    if (this.level().isEmptyBlock(checkPos) &&
                            this.level().isEmptyBlock(checkPos.above())) {
                        return new Vec3(
                                checkPos.getX() + 0.5d,
                                checkPos.getY(),
                                checkPos.getZ() + 0.5d
                        );
                    }
                }
            }
        }

        // 如果没有找到合适位置，返回当前位置
        return position();
    }

    @Override
    @NotNull
    public Packet<ClientGamePacketListener> getAddEntityPacket() {
        return NetworkHooks.getEntitySpawningPacket(this);
    }

    @Override
    public boolean isAttackable() {
        return false;
    }

    @Override
    protected void defineSynchedData() {
        // 座椅实体不需要同步数据
    }

    @Override
    public void addAdditionalSaveData(@NotNull CompoundTag compound) {
        if (this.linkedBlockPos != null) {
            compound.putInt("LinkedBlockX", this.linkedBlockPos.getX());
            compound.putInt("LinkedBlockY", this.linkedBlockPos.getY());
            compound.putInt("LinkedBlockZ", this.linkedBlockPos.getZ());
        }
    }

    @Override
    public void readAdditionalSaveData(@NotNull CompoundTag compound) {
        this.linkedBlockPos = new BlockPos(
                compound.getInt("LinkedBlockX"),
                compound.getInt("LinkedBlockY"),
                compound.getInt("LinkedBlockZ")
        );
    }

    // Getter 和 Setter 方法

    public BlockPos getLinkedBlockPos() {
        return this.linkedBlockPos;
    }

    public void setLinkedBlockPos(BlockPos blockPos) {
        this.linkedBlockPos = blockPos;
    }

    public boolean isActive() {
        return !this.isRemoving;
    }

    public void setRemoving(boolean removing) {
        this.isRemoving = removing;
    }

    /**
     * 安全地移除座椅实体
     */
    public void safeRemove() {
        if (!this.level().isClientSide()) {
            // 先释放所有乘客
            getPassengers().forEach(this::removePassenger);
            // 然后移除实体
            discard();
        }
    }
}
