package com.trunksbomb.minetriad.item;

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

import com.trunksbomb.minetriad.card.CardDefinition;
import com.trunksbomb.minetriad.card.CardRegistry;
import com.trunksbomb.minetriad.card.CardStackData;
import com.trunksbomb.minetriad.client.render.TriadCardItemRenderer;
import com.trunksbomb.minetriad.registry.TriadDataComponents;

import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.neoforged.neoforge.client.extensions.common.IClientItemExtensions;

public class CardItem extends Item {
    public CardItem(Properties properties) {
        super(properties);
    }

    @Override
    public Component getName(ItemStack stack) {
        CardStackData cardData = stack.get(TriadDataComponents.CARD_DATA);
        if (cardData == null || cardData.equals(CardStackData.EMPTY)) {
            return super.getName(stack);
        }

        CardDefinition card = CardRegistry.get(cardData.cardId());
        return Component.literal("[MT:" + card.level() + "] ")
                .append(card.name().copy())
                .withStyle(card.rarity().formatting());
    }

    @Override
    public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltipComponents, TooltipFlag tooltipFlag) {
        CardStackData cardData = stack.get(TriadDataComponents.CARD_DATA);
        if (cardData == null || cardData.equals(CardStackData.EMPTY)) {
            tooltipComponents.add(Component.literal("Unassigned card").withStyle(ChatFormatting.GRAY));
            return;
        }

        CardDefinition card = CardRegistry.get(cardData.cardId());
        tooltipComponents.add(Component.literal("Level " + card.level()).withStyle(ChatFormatting.GRAY));
        tooltipComponents.add(Component.literal("Top " + card.top() + "  Right " + card.right()).withStyle(ChatFormatting.GRAY));
        tooltipComponents.add(Component.literal("Bottom " + card.bottom() + "  Left " + card.left()).withStyle(ChatFormatting.GRAY));
        tooltipComponents.add(Component.literal(card.rarity().name()).withStyle(card.rarity().formatting()));
    }

    @Override
    public void initializeClient(Consumer<IClientItemExtensions> consumer) {
        consumer.accept(new IClientItemExtensions() {
            @Override
            public net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer getCustomRenderer() {
                return TriadCardItemRenderer.getInstance();
            }
        });
    }

    public static ItemStack createCardStack(ResourceLocation cardId, Item item) {
        ItemStack stack = new ItemStack(item);
        stack.set(TriadDataComponents.CARD_DATA, new CardStackData(cardId));
        return stack;
    }
}
