package top.r3944realms.lib39.client.renderer.item;

import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.PlayerSkin;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.core.component.DataComponents;
import net.minecraft.resources.Identifier;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.component.ResolvableProfile;
import org.jetbrains.annotations.NotNull;
import top.r3944realms.lib39.Lib39;
import top.r3944realms.lib39.client.model.DollModel;
import top.r3944realms.lib39.content.item.DollItem;
import top.r3944realms.lib39.util.GameProfileHelper;
import top.r3944realms.lib39.util.lang.Pair;

/**
 * The type Doll item renderer.
 */
public class DollItemRenderer extends BlockEntityWithoutLevelRenderer {
    private static DollItemRenderer instance;
    private DollModel dollModel;
    private boolean initialized = false;
    private DollItemRenderer() {
        super(
                Minecraft.getInstance().getBlockEntityRenderDispatcher(),
                Minecraft.getInstance().getEntityModels()
        );
    }
    private void lazyInit() {
        if (!initialized) {
            try {
                // 确保 Minecraft 实例已初始化
                Minecraft mc = Minecraft.getInstance();
                mc.getEntityModels();
                this.dollModel = new DollModel(
                        mc.getEntityModels().bakeLayer(DollModel.LAYER_LOCATION)
                );
                initialized = true;
                Lib39.LOGGER.info("Doll model initialized successfully");
            } catch (Exception e) {
                Lib39.LOGGER.error("Failed to initialize doll model", e);
            }
        }
    }

    /**
     * Gets instance.
     *
     * @return the instance
     */
    public static DollItemRenderer getInstance() {
        if (instance == null) {
            instance = new DollItemRenderer();
        }
        return instance;
    }
    @Override
    public void renderByItem(@NotNull ItemStack stack, @NotNull ItemDisplayContext displayContext,
                             @NotNull PoseStack poseStack, @NotNull MultiBufferSource buffer,
                             int packedLight, int packedOverlay) {
        if (!(stack.getItem() instanceof DollItem)) {
            return;
        }
        lazyInit();

        // 直接从 DataComponents.PROFILE 获取 ResolvableProfile
        ResolvableProfile profile = stack.get(DataComponents.PROFILE);
        Pair<Identifier, PlayerSkin.Model> skinInfo = getSkinInfo(profile);

        poseStack.pushPose();
        VertexConsumer vertexConsumer = buffer.getBuffer(RenderType.entityTranslucent(skinInfo.first));

        poseStack.translate(0.5, 2.6, 0.8);
        poseStack.scale(1.8F, -1.8F, -1.8F);
        poseStack.mulPose(Axis.YP.rotationDegrees(180));

        this.dollModel.slim = skinInfo.second == PlayerSkin.Model.SLIM;
        this.dollModel.renderToBuffer(poseStack, vertexConsumer, packedLight, packedOverlay, -1);

        poseStack.popPose();
    }

    /**
     * 获取皮肤纹理和模型类型（1.21+ 版本）
     */
    public static @NotNull Pair<Identifier, PlayerSkin.Model> getSkinInfo(@NotNull ResolvableProfile profile) {
        SkinManager skinManager = Minecraft.getInstance().getSkinManager();

        if (profile != null && profile.gameProfile() != null) {
            PlayerSkin skin = skinManager.getInsecureSkin(profile.gameProfile());
            return Pair.of(skin.texture(), skin.model());
        }

        // 默认返回 Steve 皮肤
        return Pair.of(DefaultPlayerSkin.getDefaultTexture(), PlayerSkin.Model.SLIM);
    }
}
