/*
 *  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.type;

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.item.context.BlockPlaceContext;
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.Blocks;
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.level.material.Fluids;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.r3944realms.eroticdungeongame.content.block.AbstractSeatBlock;
import top.r3944realms.eroticdungeongame.content.block.multiply.IHasPrimaryPart;
import top.r3944realms.eroticdungeongame.content.block.part.HollowFrame3x3Part;
import top.r3944realms.eroticdungeongame.core.register.EDGBlockEntities;
import top.r3944realms.lib39.util.shape.ShapeUtil;

import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;

public class MetalFrameBlock extends AbstractSeatBlock implements IHasPrimaryPart<HollowFrame3x3Part> {
    public static final EnumProperty<HollowFrame3x3Part> PART =
            EnumProperty.create("part", HollowFrame3x3Part.class);
    public MetalFrameBlock() {
        super(Properties
                .copy(Blocks.IRON_BLOCK)
        );
        registerDefaultState(
                setPrimaryStatePart(
                        getStateDefinition().any()
                                .setValue(PART, getPrimaryPart())
                                .setValue(FACING, Direction.NORTH)
                                .setValue(OCCUPIED, Boolean.FALSE)
                                .setValue(FLIPPED, Boolean.FALSE)
                                .setValue(WATERLOGGED, Boolean.FALSE)
                )
        );
    }

    @Override
    public void setupShape() {
        VoxelShape h1 = ShapeUtil.builder()
                .addPixelBox(0, 6, 14, 10, 8, 16)
                .addPixelBox(8, 0, 14, 10, 6, 16).build();
        VoxelShape h2 = ShapeUtil.builder()
                .addPixelBox(0, 6, 14, 16, 8, 16).build();
        VoxelShape h3 = ShapeUtil.builder()
                .addPixelBox(6, 0, 14, 8, 6, 16)
                .addPixelBox(6, 6, 14, 16, 8, 16).build();

        VoxelShape c1 = ShapeUtil.builder()
                .addPixelBox(8, 0, 14, 9, 16, 16).build();
        VoxelShape c3 = ShapeUtil.builder()
                .addPixelBox(7, 0, 14, 8, 16, 16).build();
        VoxelShape f1 = ShapeUtil.builder()
                .addPixelBox(0, 2, 14, 7, 4, 16)
                .addPixelBox(7, 0, 14, 9, 2, 16)
                .addPixelBox(7, 2, 14, 9, 16, 16).build();
        VoxelShape f2 = ShapeUtil.builder()
                .addPixelBox(0, 2, 14, 16, 4, 16).build();

        VoxelShape f3 = ShapeUtil.builder()
                .addPixelBox(9, 2, 14, 16, 4, 16)
                .addPixelBox(7, 2, 14, 9, 16, 16)
                .addPixelBox(7, 0, 14, 9, 2, 16).build();
        EnumMap<HollowFrame3x3Part, Map<Direction, VoxelShape>> shapes = new EnumMap<>(HollowFrame3x3Part.class);
        shapes.put(HollowFrame3x3Part.HEAD_1, ShapeUtil.createUniformDirectionMap(h1));
        shapes.put(HollowFrame3x3Part.HEAD_2, ShapeUtil.createUniformDirectionMap(h2));
        shapes.put(HollowFrame3x3Part.HEAD_3, ShapeUtil.createUniformDirectionMap(h3));
        shapes.put(HollowFrame3x3Part.MIDDLE_1, ShapeUtil.createUniformDirectionMap(c1));
        shapes.put(HollowFrame3x3Part.MIDDLE_3, ShapeUtil.createUniformDirectionMap(c3));
        shapes.put(HollowFrame3x3Part.FOOT_1, ShapeUtil.createUniformDirectionMap(f1));
        shapes.put(HollowFrame3x3Part.FOOT_2, ShapeUtil.createUniformDirectionMap(f2));
        shapes.put(HollowFrame3x3Part.FOOT_3, ShapeUtil.createUniformDirectionMap(f3));
        setPartMap(shapes);
    }

    @Override
    public HollowFrame3x3Part getPrimaryPart() {
        return HollowFrame3x3Part.FOOT_2;
    }

    @Override
    public BlockPos[] getAllPartPos(@NotNull Level level, @NotNull BlockPos pos) {
        BlockPos primaryPartPos = getPrimaryPartPos(level.getBlockState(pos), pos);
        if (primaryPartPos != null) {
            BlockPos[] otherPartPositions = getOtherPartPositions(primaryPartPos, level.getBlockState(primaryPartPos));
            BlockPos[] allPos = Arrays.copyOf(otherPartPositions, otherPartPositions.length + 1);
            allPos[allPos.length - 1] = primaryPartPos;
            return allPos;
        }
        return new BlockPos[]{};
    }

    @Override
    public BlockPos getPrimaryPartPos(BlockState blockState, BlockPos blockPos) {
        HollowFrame3x3Part part = blockState.getValue(PART);
        Direction facing = blockState.getValue(FACING);
        final Direction opposite = facing.getCounterClockWise().getOpposite();
        Direction counterClockWise = facing.getCounterClockWise();
        return switch (part) {
            case HEAD_1 -> blockPos.below(2).relative(counterClockWise);
            case HEAD_2 -> blockPos.below(2);
            case HEAD_3 -> blockPos.below(2).relative(opposite);
            case MIDDLE_1 -> blockPos.below().relative(counterClockWise);
            case MIDDLE_3 ->  blockPos.below().relative(opposite);
            case FOOT_1 -> blockPos.relative(counterClockWise);
            case FOOT_2 -> blockPos;
            case FOOT_3 -> blockPos.relative(opposite);
        };
    }

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

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

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

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

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

    @Override
    public @NotNull VoxelShape getShape(@NotNull BlockState blockState, @NotNull BlockGetter blockGetter, @NotNull BlockPos blockPos, @NotNull CollisionContext collisionContext) {
        HollowFrame3x3Part 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 super.canSurvive(state, level, pos);
    }

    private BlockPos @NotNull [] getOtherPartPositions(@NotNull BlockPos pos, @NotNull BlockState state) {
        HollowFrame3x3Part part = state.getValue(PART);
        Direction facing = state.getValue(FACING);
        return getOtherPartPositions(pos, part, facing);
    }

    @Contract("_, _, _ -> new")
    private BlockPos @NotNull [] getOtherPartPositions(@NotNull BlockPos pos, HollowFrame3x3Part part, @NotNull Direction facing) {
        Direction oppositeDir = facing.getCounterClockWise().getOpposite();
        Direction counterClockWiseDir = facing.getCounterClockWise();
        BlockPos above = pos.above();
        BlockPos above2 = pos.above(2);
        BlockPos below = pos.below();
        BlockPos below2 = pos.below(2);
        BlockPos opposite = pos.relative(oppositeDir);
        BlockPos counterClock = pos.relative(counterClockWiseDir);
        return switch (part) {
            case HEAD_1 -> new BlockPos[]{
                    below2,
                    below2.relative(counterClockWiseDir),
                    below2.relative(counterClockWiseDir, 2),
                    below,
                    below.relative(counterClockWiseDir, 2),
                    opposite,
                    pos.relative(counterClockWiseDir, 2),
            };
            case HEAD_2 ->  new BlockPos[]{
                    below2.relative(oppositeDir),
                    below2,
                    below2.relative(counterClockWiseDir),
                    below.relative(oppositeDir),
                    below.relative(counterClockWiseDir),
                    opposite,
                    counterClock
            };
            case HEAD_3 -> new BlockPos[]{
                    below2,
                    below2.relative(counterClockWiseDir),
                    below2.relative(counterClockWiseDir, 2),
                    below,
                    below.relative(counterClockWiseDir, 2),
                    counterClock,
                    pos.relative(counterClockWiseDir, 2),
            };
            case MIDDLE_1 ->  new BlockPos[]{
                    above,
                    above.relative(counterClockWiseDir),
                    above.relative(counterClockWiseDir, 2),
                    below,
                    below.relative(counterClockWiseDir, 2),
                    below.relative(counterClockWiseDir),
                    pos.relative(counterClockWiseDir, 2),
            };
            case MIDDLE_3 -> new BlockPos[]{
                    above,
                    above.relative(oppositeDir),
                    above.relative(oppositeDir, 2),
                    below,
                    below.relative(oppositeDir, 2),
                    below.relative(oppositeDir),
                    pos.relative(oppositeDir, 2),
            };
            case FOOT_1 -> new BlockPos[]{
                    above2.relative(counterClockWiseDir),
                    above2.relative(counterClockWiseDir, 2),
                    above2,
                    above,
                    above.relative(counterClockWiseDir, 2),
                    pos.relative(counterClockWiseDir),
                    pos.relative(counterClockWiseDir, 2),
            };
            case FOOT_2 -> new BlockPos[]{
                    above2.relative(oppositeDir),
                    above2,
                    above2.relative(counterClockWiseDir),
                    above.relative(oppositeDir),
                    above.relative(counterClockWiseDir),
                    opposite,
                    counterClock
            };
            case FOOT_3 -> new BlockPos[]{
                    above2.relative(oppositeDir),
                    above2.relative(oppositeDir, 2),
                    above2,
                    above,
                    above.relative(oppositeDir, 2),
                    pos.relative(oppositeDir),
                    pos.relative(oppositeDir, 2),
            };
        };
    }

    @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);
    }
    @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);
    }

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

    public BlockState setPrimaryStatePart(@NotNull BlockState state) {
        return state.setValue(PART, getPrimaryPart());
    }


    @Override
    public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) {
        Direction direction = context.getHorizontalDirection().getOpposite();
        BlockPos pos = context.getClickedPos();
        Level level = context.getLevel();

        // 检查其它位置是否可以放置
        BlockPos[] otherPartPositions = getOtherPartPositions(pos, getPrimaryPart(), direction);
        for (BlockPos otherPos : otherPartPositions) {
            if (!level.getBlockState(otherPos).canBeReplaced() || !level.getWorldBorder().isWithinBounds(otherPos)) {
                return null;
            }
        }
        return this.defaultBlockState()
                .setValue(FACING, direction)
                .setValue(PART, getPrimaryPart());
    }

    private void placeOtherParts(@NotNull Level level, @NotNull BlockPos pos, @NotNull BlockState state,
                                 @Nullable LivingEntity placer, @NotNull ItemStack stack) {
        Direction facing = state.getValue(FACING);
        boolean flipped = state.getValue(FLIPPED);

        // 获取所有其他部件的位置
        BlockPos[] otherPositions = getOtherPartPositions(pos, state);

        // 定义所有部件类型（除了主部件 FOOT_2）
        HollowFrame3x3Part[] parts = {
                HollowFrame3x3Part.HEAD_1, HollowFrame3x3Part.HEAD_2, HollowFrame3x3Part.HEAD_3,
                HollowFrame3x3Part.MIDDLE_1, HollowFrame3x3Part.MIDDLE_3,
                HollowFrame3x3Part.FOOT_1, HollowFrame3x3Part.FOOT_3
        };

        // 放置各个部件
        for (int i = 0; i < otherPositions.length && i < parts.length; i++) {
            BlockPos otherPos = otherPositions[i];
            HollowFrame3x3Part part = parts[i];

            if (level.getBlockState(otherPos).canBeReplaced()) {
                BlockState partState = defaultBlockState()
                        .setValue(FACING, facing)
                        .setValue(PART, part)
                        .setValue(OCCUPIED, Boolean.FALSE)
                        .setValue(FLIPPED, flipped)
                        .setValue(WATERLOGGED, level.getFluidState(otherPos).getType() == Fluids.WATER);

                level.setBlock(otherPos, partState, Block.UPDATE_ALL);
            }
        }

        // 更新方块状态
        level.blockUpdated(pos, Blocks.AIR);
        state.updateNeighbourShapes(level, pos, Block.UPDATE_ALL);
    }

    private void handleOtherPartsRemoval(@NotNull Level level, @NotNull BlockPos blockPos, @NotNull BlockState blockState) {
        BlockPos[] otherPartPositions = getOtherPartPositions(blockPos, blockState);
        for (BlockPos otherPos : otherPartPositions) {
            removeIfSameBlock(level, otherPos);
        }
    }
}
