/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.content.block.multiply;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.r3944realms.eroticdungeongame.content.block.AbstractSeatBlock;
import top.r3944realms.eroticdungeongame.content.block.part.SeatPart;
import top.r3944realms.eroticdungeongame.core.register.EDGBlockEntities;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unused")
public abstract class AbstractTwoPartSeatBlock extends AbstractSeatBlock implements IHasPrimaryPart<SeatPart> {
    public static final EnumProperty<SeatPart> PART = EnumProperty.create("part", SeatPart.class);
    public AbstractTwoPartSeatBlock(Properties properties) {
        super(properties);
        registerDefaultState(
                getStateDefinition().any()
                        .setValue(PART, getPrimaryPart())
                        .setValue(FACING, Direction.NORTH)
                        .setValue(OCCUPIED, Boolean.FALSE)
                        .setValue(FLIPPED, Boolean.FALSE)
                        .setValue(WATERLOGGED, Boolean.FALSE)
        );
    }

    @Override
    public final @Nullable BlockEntity newBlockEntity(@NotNull BlockPos blockPos, @NotNull BlockState blockState) {
        // 只在主部件创建BlockEntity
        if (isPrimary(blockState)) {
            return createPrimaryBlockEntity(blockPos, blockState);
        }
        return null;
    }

    @Override
    public BlockPos[] getAllPartPos(@NotNull Level level, @NotNull BlockPos pos) {
        List<BlockPos> result = new ArrayList<>();
        BlockState blockState = level.getBlockState(pos);
        Direction direction = blockState.getValue(FACING);
        SeatPart part = blockState.getValue(PART);
        BlockPos primaryPartPos = getPrimaryPartPos(blockState, pos);
        result.add(primaryPartPos);
        result.add(getSecondaryPartPos(primaryPartPos, direction, part));
        return result.toArray(new BlockPos[0]);
    }

    @Override
    public void setPartMap(Map<SeatPart, Map<Direction, VoxelShape>> map) {
        CLASS_CACHE.put(getClass(), map);
    }

    @Override
    public BlockEntity createPrimaryBlockEntity(@NotNull BlockPos blockPos, @NotNull BlockState blockState) {
        return EDGBlockEntities.DEFAULT_SEAT_BLOCK_ENTITY.get().create(blockPos, blockState);
    }

    // 坑: Forge初始化渲染形状时会加载一次方块形状， 具体实现未<init> 需返回默认值
    @Override
    public @NotNull VoxelShape getShape(@NotNull BlockState blockState, @NotNull BlockGetter blockGetter,
                                        @NotNull BlockPos blockPos, @NotNull CollisionContext collisionContext) {
        SeatPart part = blockState.getValue(PART);
        Direction facing = blockState.getValue(FACING);
        Map<Direction, VoxelShape> map = getShapeCacheMap(part);
        if (isCacheInitialized(part) && map.containsKey(facing)) {
            return map.get(facing);
        }
        return super.getShape(blockState, blockGetter, blockPos, collisionContext);
    }

    @Override
    protected void createBlockStateDefinition(StateDefinition.@NotNull Builder<Block, BlockState> builder) {
        super.createBlockStateDefinition(builder);
        builder.add(PART);
    }

    /**
     * 抽象方法：获取从部件的相对位置
     * @param primaryPos 主部件位置
     * @param facing 朝向
     * @return 从部件位置
     */
    protected abstract BlockPos getSecondaryPartPos(BlockPos primaryPos, Direction facing, SeatPart currentPart);

    /**
     * 抽象方法：放置从部件
     */
    protected abstract void placeSecondaryPart(Level level, BlockPos primaryPos, BlockState primaryState,
                                               LivingEntity placer, ItemStack stack);

    /**
     * 抽象方法：移除时处理从部件
     */
    protected abstract void handleSecondaryPartRemoval(Level level, BlockPos blockPos, BlockState blockState);

    @Override
    public void setPlacedBy(@NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState state,
                            @Nullable LivingEntity placer, @NotNull ItemStack stack) {
        super.setPlacedBy(level, pos, state, placer, stack);
        if (!level.isClientSide) {
            // 放置从部件
            placeSecondaryPart(level, pos, state, placer, stack);
        }
    }

    @Override
    public @NotNull InteractionResult use(@NotNull BlockState blockState, @NotNull Level level,
                                          @NotNull BlockPos blockPos, @NotNull Player player,
                                          @NotNull InteractionHand hand, @NotNull BlockHitResult hitResult) {
        // 获取主部件位置进行交互
        BlockPos primaryPos = getPrimaryPartPos(blockState, blockPos);
        return useOnPrimaryPart(blockState, level, primaryPos, player, hand, hitResult);
    }

    @Override
    public InteractionResult useOnPrimaryPart(@NotNull BlockState useBlockState, @NotNull Level level, @NotNull BlockPos primaryBlockPos, @NotNull Player player, @NotNull InteractionHand hand, @NotNull BlockHitResult hitResult) {
        return handleSeatInteraction(useBlockState, level, primaryBlockPos, player, hand, hitResult);
    }

    @Override
    public void onRemove(@NotNull BlockState blockState, @NotNull Level level, @NotNull BlockPos blockPos,
                         @NotNull BlockState newState, boolean moved) {
        if (blockState.getBlock() != newState.getBlock()) {
            // 处理从部件的移除
            handleSecondaryPartRemoval(level, blockPos, blockState);
        }
        super.onRemove(blockState, level, blockPos, newState, moved);
    }

    /**
     * 检查是否可以作为多部分方块放置
     */
    @SuppressWarnings("deprecation")
    @Override
    public boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader level, @NotNull BlockPos pos) {
        // 检查从部件位置是否可以放置
        BlockPos secondaryPos = getSecondaryPartPos(pos, state.getValue(FACING), state.getValue(PART));
        return level.getBlockState(secondaryPos).canBeReplaced() &&
                super.canSurvive(state, level, pos);
    }

    @Nullable
    @Override
    public BlockEntity getBlockEntity(BlockState state, @NotNull Level level, BlockPos pos) {
        return super.getBlockEntity(state, level, pos);
    }

    /**
     * 获取从部件的方块状态
     */
    public BlockState setSecondaryState(@NotNull BlockState currentState) {
        return currentState.setValue(PART, SeatPart.HEAD);
    }

    @Override
    public SeatPart getPrimaryPart() {
        return SeatPart.FOOT;
    }

    @Override
    public EnumProperty<SeatPart> getPartProperty() {
        return PART;
    }
}