/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.block;

import com.remains_cave.block.entity.TrialVaultBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.ItemInteractionResult;
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.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.SoundType;
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.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.material.MapColor;
import net.minecraft.world.phys.BlockHitResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class TrialVaultBlock extends Block implements EntityBlock {
    private final TrialVaultType type;
    public TrialVaultType getType() {
        return type;
    }
    public TrialVaultBlock(TrialVaultType type) {
        super(Properties.of()
                .mapColor(MapColor.METAL)
                .strength(2.0F, 6.0F)
                .sound(SoundType.VAULT)          // 使用原版宝库音效
                .noOcclusion());
        this.type = type;
        this.registerDefaultState(this.stateDefinition.any()
                .setValue(VAULT_STATE, VaultState.INACTIVE)
                .setValue(FACING, Direction.NORTH));
    }

    @Override
    public int getLightEmission(BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos) {
        VaultState vaultState = state.getValue(VAULT_STATE);
        return switch (vaultState) {
            case ACTIVE, EJECTING -> 12;
            default -> 6;
        };
    }

    public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
    @Override
    public BlockState getStateForPlacement(BlockPlaceContext context) {
        return this.defaultBlockState()
                .setValue(FACING, context.getHorizontalDirection().getOpposite());
    }

    @Override
    protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
        builder.add(VAULT_STATE, FACING);
    }
    // 在 TrialVaultBlock 类中添加
    public static final EnumProperty<VaultState> VAULT_STATE = EnumProperty.create("vault_state", VaultState.class);

    // TrialVaultBlock.java 中添加
    @Override
    public void tick(@NotNull BlockState state, ServerLevel level, @NotNull BlockPos pos, @NotNull RandomSource random) {
        if (level.getBlockEntity(pos) instanceof TrialVaultBlockEntity vault) {
            vault.startEjecting();
        }
    }



    public enum VaultState implements StringRepresentable {
        INACTIVE("inactive"),
        ACTIVE("active"),
        EJECTING("ejecting");

        private final String name;

        VaultState(String name) { this.name = name; }

        @Override
        public @NotNull String getSerializedName() { return name; }
    }

    public static final BooleanProperty OMINOUS = BooleanProperty.create("ominous");

    @Nullable
    @Override
    public BlockEntity newBlockEntity(@NotNull BlockPos pos, @NotNull BlockState state) {
        return new TrialVaultBlockEntity(pos, state, type);
    }

    @Override
    protected @NotNull InteractionResult useWithoutItem(@NotNull BlockState state, Level level, @NotNull BlockPos pos, @NotNull Player player, @NotNull BlockHitResult hitResult) {
        if (!(level.getBlockEntity(pos) instanceof TrialVaultBlockEntity vault)) {
            return InteractionResult.PASS;
        }
        return vault.use(player);
    }
    @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, @NotNull BlockState state, @NotNull BlockEntityType<T> type) {
        if (type == ModBlocks.TRIAL_VAULT_BLOCK_ENTITY.get()) {
            if (level.isClientSide) {
                return (lvl, pos, st, be) -> ((TrialVaultBlockEntity) be).clientTick();
            } else {
                return (lvl, pos, st, be) -> TrialVaultBlockEntity.serverTick(lvl, pos, st, (TrialVaultBlockEntity) be);
            }
        }
        return null;
    }

    // 可选：处理有物品的交互（主要使用 useWithoutItem 或统一使用 use）
    @Override
    protected @NotNull ItemInteractionResult useItemOn(@NotNull ItemStack stack, @NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull Player player, @NotNull InteractionHand hand, @NotNull BlockHitResult hitResult) {
        InteractionResult result = useWithoutItem(state, level, pos, player, hitResult);
        if (result.consumesAction()) {
            return ItemInteractionResult.sidedSuccess(level.isClientSide);
        }
        return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION;
    }
}