/*
 *  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.multiply.horizontal.HorizontalTriplePlankSeatBlock;
import top.r3944realms.eroticdungeongame.content.block.part.AdvanceSeatPart;
import top.r3944realms.eroticdungeongame.core.register.EDGBlockEntities;

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

public abstract class AbstractThreePartSeatBlock extends AbstractSeatBlock implements IHasPrimaryPart<AdvanceSeatPart> {
    public static final EnumProperty<AdvanceSeatPart> PART =
            EnumProperty.create("part", AdvanceSeatPart.class);

    public AbstractThreePartSeatBlock(Properties properties) {
        super(properties);
        registerDefaultState(
                setPrimaryStatePart(
                        getStateDefinition().any()
                        .setValue(PART, getPrimaryPart())
                        .setValue(FACING, Direction.NORTH)
                        .setValue(OCCUPIED, Boolean.FALSE)
                        .setValue(FLIPPED, Boolean.FALSE)
                        .setValue(WATERLOGGED, Boolean.FALSE)
                )
        );
    }

    /**
     * 抽象方法：获取中间部件的位置
     * @param primaryPos 主部件位置
     * @param facing 朝向
     * @return 中间部件位置
     */
    protected abstract BlockPos getMiddlePartPos(BlockPos primaryPos, Direction facing);

    /**
     * 抽象方法：获取顶部部件的位置
     * @param primaryPos 主部件位置
     * @param facing 朝向
     * @return 顶部部件位置
     */
    protected abstract BlockPos getTopPartPos(BlockPos primaryPos, Direction facing);

    /**
     * 抽象方法：根据当前部分获取其他部分位置
     */
    public abstract BlockPos[] getOtherPartPositions(BlockPos currentPos, BlockState currentState);

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

    @Override
    public BlockPos[] getAllPartPos(@NotNull Level level, @NotNull BlockPos pos) {
        List<BlockPos> result = new ArrayList<>();
        BlockState blockState = level.getBlockState(pos);
        List<BlockPos> list;
        if (blockState.getBlock() instanceof HorizontalTriplePlankSeatBlock plankSeatBlock) { // 特殊情况
            list = Arrays.asList(plankSeatBlock.getOtherPartPositions(pos, blockState.getValue(PART), blockState.getValue(FACING)));
        } else list = Arrays.asList(getOtherPartPositions(pos, blockState));
        BlockPos primaryPartPos = getPrimaryPartPos(blockState, pos);
        result.add(primaryPartPos);
        result.addAll(list);
        return result.toArray(new BlockPos[0]);
    }

    protected void handleOtherPartsRemoval(Level level, BlockPos blockPos, BlockState blockState) {
        BlockPos[] otherPartPositions = getOtherPartPositions(blockPos, blockState);
        for (BlockPos otherPos : otherPartPositions) {
            removeIfSameBlock(level, otherPos);
        }
    }
    @Override
    public final @Nullable BlockEntity newBlockEntity(@NotNull BlockPos blockPos, @NotNull BlockState blockState) {
        // 只在主部件创建BlockEntity
        if (isPrimary(blockState)) {
            return createPrimaryBlockEntity(blockPos, blockState);
        }
        return null;
    }

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

    @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
    protected void createBlockStateDefinition(StateDefinition.@NotNull Builder<Block, BlockState> builder) {
        super.createBlockStateDefinition(builder);
        builder.add(PART);
    }

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

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

    @Override
    public AdvanceSeatPart getPrimaryPart() {
        return AdvanceSeatPart.FOOT;
    }
    @Override
    public @NotNull VoxelShape getShape(@NotNull BlockState blockState, @NotNull BlockGetter blockGetter,
                                        @NotNull BlockPos blockPos, @NotNull CollisionContext collisionContext) {
        AdvanceSeatPart 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);
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean canSurvive(@NotNull BlockState state, @NotNull LevelReader level, @NotNull BlockPos pos) {
        // 检查所有其他部件位置是否可以放置
        BlockPos[] otherPositions = getOtherPartPositions(pos, state);

        for (BlockPos otherPos : otherPositions) {
            if (!level.getBlockState(otherPos).canBeReplaced()) {
                return false;
            }
        }

        return true;
    }
    @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) {
            // 放置其他部件
            placeOtherParts(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 void onRemove(@NotNull BlockState blockState, @NotNull Level level, @NotNull BlockPos blockPos,
                         @NotNull BlockState newState, boolean moved) {
        if (blockState.getBlock() != newState.getBlock()) {
            // 处理其他部件的移除
            handleOtherPartsRemoval(level, blockPos, blockState);
        }
        super.onRemove(blockState, level, blockPos, newState, moved);
    }

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

}
