package com.tiedup.remake.client.events;

import com.mojang.blaze3d.systems.RenderSystem;
import com.tiedup.remake.core.ModConfig;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.PlayerBindState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.HumanoidArm;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RenderGuiOverlayEvent;
import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

/**
 *
 * Based on the original TiedUp! mod (1.12.2) by Yuti & Marl Velius.
 *
 * The original approach:
 * 1. Render blindfold texture over the entire screen (covers everything)
 * 2. Manually redraw the hotbar on top of the blindfold
 *
 * This ensures the hotbar remains visible while the game world is obscured.
 */
@Mod.EventBusSubscriber(
    modid = TiedUpMod.MOD_ID,
    bus = Mod.EventBusSubscriber.Bus.FORGE,
    value = Dist.CLIENT
)
public class BlindfoldRenderEventHandler {

    private static final ResourceLocation BLINDFOLD_TEXTURE =
        ResourceLocation.fromNamespaceAndPath(
            TiedUpMod.MOD_ID,
            "textures/misc/blindfolded.png"
        );

    // Vanilla widgets texture (contains hotbar graphics)
    private static final ResourceLocation WIDGETS_TEXTURE =
        ResourceLocation.fromNamespaceAndPath(
            "minecraft",
            "textures/gui/widgets.png"
        );

    private static boolean wasBlindfolded = false;

    /**
     * Render the blindfold overlay AFTER the hotbar is rendered.
     * Then redraw the hotbar on top of the blindfold (original mod approach).
     */
    @SubscribeEvent
    public static void onRenderGuiPost(RenderGuiOverlayEvent.Post event) {
        // Render after HOTBAR (same as original mod)
        if (event.getOverlay() != VanillaGuiOverlay.HOTBAR.type()) {
            return;
        }

        Minecraft mc = Minecraft.getInstance();
        LocalPlayer player = mc.player;

        // Safety checks
        if (player == null || mc.options.hideGui) {
            return;
        }

        // Non-hardcore mode: hide blindfold when a GUI screen is open
        boolean hardcore = ModConfig.CLIENT.hardcoreBlindfold.get();
        if (!hardcore && mc.screen != null) {
            return;
        }

        // Get player state
        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) {
            return;
        }

        boolean isBlindfolded = state.isBlindfolded();

        // Log state changes only
        if (isBlindfolded != wasBlindfolded) {
            if (isBlindfolded) {
                TiedUpMod.LOGGER.info(
                    "[BLINDFOLD] Player is now blindfolded - rendering overlay"
                );
            } else {
                TiedUpMod.LOGGER.info(
                    "[BLINDFOLD] Player is no longer blindfolded - stopping overlay"
                );
            }
            wasBlindfolded = isBlindfolded;
        }

        // Only render if blindfolded
        if (!isBlindfolded) {
            return;
        }

        try {
            int screenWidth = mc.getWindow().getGuiScaledWidth();
            int screenHeight = mc.getWindow().getGuiScaledHeight();

            // Set opacity: hardcore forces full opacity, otherwise use config
            float opacity = hardcore
                ? 1.0F
                : ModConfig.CLIENT.blindfoldOverlayOpacity.get().floatValue();
            RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, opacity);
            RenderSystem.enableBlend();
            RenderSystem.defaultBlendFunc();

            // Step 1: Render the blindfold texture over the entire screen
            event
                .getGuiGraphics()
                .blit(
                    BLINDFOLD_TEXTURE,
                    0,
                    0,
                    0.0F,
                    0.0F,
                    screenWidth,
                    screenHeight,
                    screenWidth,
                    screenHeight
                );

            // Reset shader color for hotbar
            RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);

            // Step 2: Redraw the hotbar on top of the blindfold (original mod approach)
            redrawHotbar(
                mc,
                event.getGuiGraphics(),
                screenWidth,
                screenHeight,
                player
            );
        } catch (RuntimeException e) {
            TiedUpMod.LOGGER.error("[BLINDFOLD] Error rendering overlay", e);
        }
    }

    /**
     * Manually redraw the hotbar on top of the blindfold texture.
     * Based on the original mod's redrawHotBar() function.
     *
     * This draws:
     * - Hotbar background (182x22 pixels)
     * - Selected slot highlight
     * - Offhand slot (if item present)
     */
    private static void redrawHotbar(
        Minecraft mc,
        GuiGraphics guiGraphics,
        int screenWidth,
        int screenHeight,
        LocalPlayer player
    ) {
        // Reset render state
        RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
        RenderSystem.enableBlend();
        RenderSystem.defaultBlendFunc();

        // Center of screen (hotbar is centered)
        int centerX = screenWidth / 2;
        int hotbarY = screenHeight - 22; // Hotbar is 22 pixels from bottom

        // Draw hotbar background (182 pixels wide, 22 pixels tall)
        // Original: this.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22, 0, 0, 182, 22);
        guiGraphics.blit(
            WIDGETS_TEXTURE,
            centerX - 91,
            hotbarY, // Position
            0,
            0, // Texture UV start
            182,
            22 // Size
        );

        // Draw selected slot highlight (24x22 pixels)
        // Original: this.drawTexturedModalRect(i - 91 - 1 + entityplayer.inventory.currentItem * 20, ...);
        int selectedSlot = player.getInventory().selected;
        guiGraphics.blit(
            WIDGETS_TEXTURE,
            centerX - 91 - 1 + selectedSlot * 20,
            hotbarY - 1, // Position (offset by selected slot)
            0,
            22, // Texture UV (highlight texture)
            24,
            22 // Size
        );

        // Draw offhand slot if player has an item in offhand
        ItemStack offhandItem = player.getItemInHand(InteractionHand.OFF_HAND);
        if (!offhandItem.isEmpty()) {
            HumanoidArm offhandSide = player.getMainArm().getOpposite();

            if (offhandSide == HumanoidArm.LEFT) {
                // Offhand on left side
                // Original: this.drawTexturedModalRect(i - 91 - 29, sr.getScaledHeight() - 23, 24, 22, 29, 24);
                guiGraphics.blit(
                    WIDGETS_TEXTURE,
                    centerX - 91 - 29,
                    hotbarY - 1, // Position
                    24,
                    22, // Texture UV
                    29,
                    24 // Size
                );
            } else {
                // Offhand on right side
                // Original: this.drawTexturedModalRect(i + 91, sr.getScaledHeight() - 23, 53, 22, 29, 24);
                guiGraphics.blit(
                    WIDGETS_TEXTURE,
                    centerX + 91,
                    hotbarY - 1, // Position
                    53,
                    22, // Texture UV
                    29,
                    24 // Size
                );
            }
        }

        RenderSystem.disableBlend();
    }
}
