/*
 *  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.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.WoodType;
import net.minecraft.world.phys.BlockHitResult;
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.ISeatBlock;
import top.r3944realms.eroticdungeongame.content.block.IWoodTypeBlock;
import top.r3944realms.eroticdungeongame.content.block.blockentity.SpanishDonkeyBlockEntity;
import top.r3944realms.eroticdungeongame.core.register.EDGBlockEntities;
import top.r3944realms.lib39.util.shape.ShapeUtil;

public class SpanishDonkeyBlock extends AbstractSeatBlock implements IWoodTypeBlock {
    private final WoodType woodType;
    // 类似活塞的EXTENDED属性，表示是否被红石激活
    public static final BooleanProperty POWERED = BooleanProperty.create("powered");

    public SpanishDonkeyBlock(WoodType woodType) {
        super(PROPERTIES);
        this.woodType = woodType;

        // 注册默认状态

        registerDefaultState(
                getStateDefinition().any()
                        .setValue(FACING, Direction.NORTH)
                        .setValue(OCCUPIED, Boolean.FALSE)
                        .setValue(FLIPPED, Boolean.FALSE)
                        .setValue(WATERLOGGED, Boolean.FALSE)
                        .setValue(POWERED, Boolean.FALSE)
        );
    }

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

    /**
     * 当周围方块变化时检测红石信号（电平触发）
     */
    @SuppressWarnings("deprecation")
    @Override
    public void neighborChanged(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull Block neighborBlock, @NotNull BlockPos fromPos, boolean movedByPiston) {
        if (!level.isClientSide) {
            boolean isPowered = level.hasNeighborSignal(pos);
            boolean wasPowered = state.getValue(POWERED);

            // 获取方块实体
            BlockEntity blockEntity = level.getBlockEntity(pos);
            if (blockEntity instanceof SpanishDonkeyBlockEntity spanishDonkeyBlock) {

                if (isPowered && !wasPowered) {
                    // 红石激活：设置shock为true
                    level.setBlock(pos, state.setValue(POWERED, true), UPDATE_ALL);
                    spanishDonkeyBlock.setShock(true);
                    spanishDonkeyBlock.setChanged();

                    // 播放激活音效
                    level.playSound(null, pos,
                            net.minecraft.sounds.SoundEvents.LEVER_CLICK,
                            net.minecraft.sounds.SoundSource.BLOCKS,
                            0.3F, 0.6F);

                } else if (!isPowered && wasPowered) {
                    // 红石失活：设置shock为false
                    level.setBlock(pos, state.setValue(POWERED, false), UPDATE_ALL);
                    spanishDonkeyBlock.setShock(false);
                    spanishDonkeyBlock.setChanged();

                    // 播放失活音效
                    level.playSound(null, pos,
                            net.minecraft.sounds.SoundEvents.LEVER_CLICK,
                            net.minecraft.sounds.SoundSource.BLOCKS,
                            0.3F, 0.5F);
                }

                // 如果状态有变化，通知客户端
                if (isPowered != wasPowered) {
                    level.sendBlockUpdated(pos, state, state.setValue(POWERED, isPowered), UPDATE_ALL);
                }
            }
        }

        super.neighborChanged(state, level, pos, neighborBlock, fromPos, movedByPiston);
    }

    /**
     * 在方块被放置时检测红石信号
     */
    @SuppressWarnings("deprecation")
    @Override
    public void onPlace(@NotNull BlockState state, Level level, @NotNull BlockPos pos, @NotNull BlockState oldState, boolean movedByPiston) {
        if (!level.isClientSide) {
            boolean isPowered = level.hasNeighborSignal(pos);

            if (isPowered != state.getValue(POWERED)) {
                level.setBlock(pos, state.setValue(POWERED, isPowered), UPDATE_ALL);

                // 更新方块实体状态
                BlockEntity blockEntity = level.getBlockEntity(pos);
                if (blockEntity instanceof SpanishDonkeyBlockEntity spanishDonkeyBlock) {
                    spanishDonkeyBlock.setShock(isPowered);
                    spanishDonkeyBlock.setShouldPlayRouting(false);
                    spanishDonkeyBlock.setShouldPlayUnrouting(false);
                    spanishDonkeyBlock.setChanged();
                }
            }
        }
        BlockEntity blockEntity = level.getBlockEntity(pos);
        if (blockEntity instanceof SpanishDonkeyBlockEntity spanishDonkeyBlock) {
            spanishDonkeyBlock.setShouldPlayRouting(false);
            spanishDonkeyBlock.setShouldPlayUnrouting(false);
        }
    }

    @Nullable
    @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(@NotNull Level pLevel, @NotNull BlockState pState, @NotNull BlockEntityType<T> pBlockEntityType) {
        return pLevel.isClientSide() ? null : ISeatBlock.createTickerHelper(pBlockEntityType, EDGBlockEntities.SPANISH_DONKEY_BLOCK_ENTITY.get(), SpanishDonkeyBlockEntity::serverTick);
    }

    @Override
    public BlockEntity newBlockEntity(@NotNull BlockPos blockPos, @NotNull BlockState blockState) {
        return new SpanishDonkeyBlockEntity(blockPos, blockState);
    }

    @Override
    public @NotNull InteractionResult use(@NotNull BlockState blockState, @NotNull Level level, @NotNull BlockPos blockPos, @NotNull Player player, @NotNull InteractionHand hand, @NotNull BlockHitResult hitResult) {
        BlockEntity blockEntity = getBlockEntity(blockState, level, blockPos);
        if (player.isShiftKeyDown() && blockEntity instanceof SpanishDonkeyBlockEntity spanishDonkeyBlock) {
            if (!spanishDonkeyBlock.isShock()) {
                spanishDonkeyBlock.toggleRoute();
                spanishDonkeyBlock.setChanged();
            }
            return InteractionResult.SUCCESS;
        } else {
            return handleSeatInteraction(blockState, level, blockPos, player, hand, hitResult);
        }
    }

    public WoodType getWoodType() {
        return woodType;
    }

    @Override
    public void setupShape() {
        VoxelShape voxelShape = ShapeUtil.builder()
                .addPixelBox(0, 6, 7, 16, 15, 9)
                .addPixelBox(0, 6, 9, 16, 11, 11)
                .addPixelBox(0, 6, 5, 16, 11, 7)
                .addPixelBox(0, 6, 5, 16, 8, 5)
                .addPixelBox(0, 6, 11, 16, 8, 12)
                .addPixelBox(0, 6, 4, 16, 8, 5)
                .addPixelBox(13, 0, 14, 16, 2.525, 15)
                .addPixelBox(13, 2.325, 13, 16, 4.45, 14)
                .addPixelBox(13, 4.475, 12, 16, 6.449999999999999, 13)
                .addPixelBox(0, 0, 1, 3, 2.525, 2)
                .addPixelBox(0, 2.325, 2, 3, 4.45, 3)
                .addPixelBox(0, 4.475, 3, 3, 6.449999999999999, 4)
                .addPixelBox(0, 4.475, 12, 3, 6.449999999999999, 13)
                .addPixelBox(0, 2.325, 13, 3, 4.45, 14)
                .addPixelBox(0, 0, 14, 3, 2.525, 15)
                .addPixelBox(13, 0, 1, 16, 2.525, 2)
                .addPixelBox(13, 2.325, 2, 16, 4.45, 3)
                .addPixelBox(13, 4.475, 3, 16, 6.449999999999999, 4)
                .build();
        setShapeCacheMap(ShapeUtil.createUniformDirectionMap(voxelShape));
    }

}
