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

import com.remains_cave.item.ModDataComponents;
import com.remains_cave.item.ModItems;
import com.remains_cave.item.client.TombQuiverArmorRenderer;
import com.remains_cave.item.client.TombQuiverRenderer;
import com.remains_cave.item.component.QuiverContent;
import com.remains_cave.item.menu.QuiverMenu;
import net.minecraft.client.model.HumanoidModel;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.SimpleMenuProvider;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BowItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import software.bernie.geckolib.animatable.GeoItem;
import software.bernie.geckolib.animatable.client.GeoRenderProvider;
import software.bernie.geckolib.animatable.instance.AnimatableInstanceCache;
import software.bernie.geckolib.animation.AnimatableManager;
import software.bernie.geckolib.renderer.GeoItemRenderer;
import software.bernie.geckolib.util.GeckoLibUtil;

import java.util.List;
import java.util.function.Consumer;

public class TombQuiverItem extends Item implements GeoItem {
    private final AnimatableInstanceCache cache = GeckoLibUtil.createInstanceCache(this);

    public TombQuiverItem(Properties properties) {
        super(properties);
    }

    public static ItemStack getFirstArrow(ItemStack quiverStack) {
        // 使用正确的自定义组件
        QuiverContent content = quiverStack.get(ModDataComponents.QUIVER_CONTENT.get());
        if (content != null) {
            List<ItemStack> arrows = content.arrows();
            for (ItemStack arrow : arrows) {
                if (!arrow.isEmpty()) {
                    return arrow;
                }
            }
        }
        return ItemStack.EMPTY;
    }

    @Override
    public void createGeoRenderer(Consumer<GeoRenderProvider> consumer) {
        consumer.accept(new GeoRenderProvider() {
            private TombQuiverRenderer itemRenderer;

            @Override
            public GeoItemRenderer<?> getGeoItemRenderer() {
                if (itemRenderer == null) itemRenderer = new TombQuiverRenderer();
                return itemRenderer;
            }

            @Override
            public <T extends LivingEntity> TombQuiverArmorRenderer getGeoArmorRenderer(
                    T livingEntity, ItemStack itemStack, EquipmentSlot equipmentSlot,
                    HumanoidModel<T> original) {
                // 每次返回新实例，避免状态残留
                return new TombQuiverArmorRenderer();
            }
        });
    }

    @Override
    public boolean isValidRepairItem(@NotNull ItemStack toRepair, ItemStack repair) {
        return repair.is(ModItems.CRIMSON_CRYSTAL.get());
    }

    @Override
    public boolean isRepairable(@NotNull ItemStack stack) {
        return true;
    }

    @Override
    public @NotNull InteractionResultHolder<ItemStack> use(Level level, Player player, @NotNull InteractionHand usedHand) {
        ItemStack quiverStack = player.getItemInHand(usedHand);

        // 条件：主手持有弓，且当前使用的箭袋在副手，且箭袋内有箭
        ItemStack mainHand = player.getMainHandItem();
        if (mainHand.getItem() instanceof BowItem && usedHand == InteractionHand.OFF_HAND) {
            QuiverContent content = quiverStack.get(ModDataComponents.QUIVER_CONTENT.get());
            if (content != null && content.arrows().stream().anyMatch(s -> !s.isEmpty())) {
                // 有箭时不应该打开 GUI，返回失败让弓继续处理
                return InteractionResultHolder.fail(quiverStack);
            }
        }
        // 如果箭袋在副手，永远不打开 GUI，让弓等其他物品处理
        if (usedHand == InteractionHand.OFF_HAND) {
            return InteractionResultHolder.fail(quiverStack);
        }
        // 原有逻辑：无上述情况时打开 GUI
        if (!level.isClientSide) {
            player.openMenu(new SimpleMenuProvider((containerId, inventory, p) ->
                    new QuiverMenu(containerId, inventory, quiverStack),
                    Component.translatable("container.remains_cave.quiver")), buf -> {});
        }
        return InteractionResultHolder.sidedSuccess(quiverStack, level.isClientSide);
    }
    @Override
    public void registerControllers(AnimatableManager.ControllerRegistrar controllers) {
        // 如果没有动画，可以留空
    }

    @Override
    public AnimatableInstanceCache getAnimatableInstanceCache() {
        return cache;
    }
}