package com.tiedup.remake.client.gui.overlays;

import com.tiedup.remake.client.ModKeybindings;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.IBondageState;
import com.tiedup.remake.util.KidnappedHelper;
import com.tiedup.remake.v2.BodyRegionV2;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
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;

/**
 * Overlay that shows a tooltip when looking at a tied player/NPC.
 * Displayed below the crosshair when aiming at a restrainable entity.
 *
 * Shows contextual hints like:
 * - "[Right-click] Untie" when looking at tied entity
 * - "[Right-click] Remove gag" when looking at gagged entity
 */
@OnlyIn(Dist.CLIENT)
@Mod.EventBusSubscriber(modid = TiedUpMod.MOD_ID, value = Dist.CLIENT)
public class UntieTooltipOverlay {

    /** Offset below the crosshair */
    private static final int Y_OFFSET = 12;

    /** Text color (white with slight transparency) */
    private static final int TEXT_COLOR = 0xFFFFFFFF;

    /** Shadow color */
    private static final int SHADOW_COLOR = 0x80000000;

    @SubscribeEvent
    public static void onRenderOverlay(RenderGuiOverlayEvent.Post event) {
        // Render after crosshair
        if (event.getOverlay() != VanillaGuiOverlay.CROSSHAIR.type()) {
            return;
        }

        Minecraft mc = Minecraft.getInstance();
        if (mc.player == null) {
            return;
        }

        // Check what we're looking at
        HitResult hitResult = mc.hitResult;
        if (!(hitResult instanceof EntityHitResult entityHit)) {
            return;
        }

        Entity target = entityHit.getEntity();
        if (!(target instanceof LivingEntity livingTarget)) {
            return;
        }

        // Get the target's kidnapped state
        IBondageState state = KidnappedHelper.getKidnappedState(livingTarget);
        if (state == null) {
            return;
        }

        // Determine what action is available
        String tooltip = getTooltipText(state);
        if (tooltip == null) {
            return;
        }

        // Render the tooltip below the crosshair
        GuiGraphics graphics = event.getGuiGraphics();
        int screenWidth = mc.getWindow().getGuiScaledWidth();
        int screenHeight = mc.getWindow().getGuiScaledHeight();

        int centerX = screenWidth / 2;
        int centerY = screenHeight / 2;

        // Draw text centered below crosshair
        int textWidth = mc.font.width(tooltip);
        int textX = centerX - textWidth / 2;
        int textY = centerY + Y_OFFSET;

        // Draw shadow first for better readability
        graphics.drawString(
            mc.font,
            tooltip,
            textX + 1,
            textY + 1,
            SHADOW_COLOR,
            false
        );
        graphics.drawString(mc.font, tooltip, textX, textY, TEXT_COLOR, false);
    }

    /**
     * Get the appropriate tooltip text based on the target's state.
     * Respects lock status - locked items show "Help struggle" instead.
     *
     * @param state The target's kidnapped state
     * @return The tooltip text, or null if no action is available
     */
    private static String getTooltipText(IBondageState state) {
        // Priority order: untie > ungag > unblindfold > uncollar
        // If item is locked, can only help struggle (not remove directly)
        String struggleKey =
            "[" +
            ModKeybindings.STRUGGLE_KEY.getTranslatedKeyMessage().getString() +
            "]";

        if (state.isTiedUp()) {
            ItemStack bind = state.getEquipment(BodyRegionV2.ARMS);
            if (state.isLocked(bind, false)) {
                return struggleKey + " Help struggle";
            }
            return "[Right-click] Untie";
        }

        if (state.isGagged()) {
            // Check if player is holding food → force feeding prompt
            Minecraft mc = Minecraft.getInstance();
            if (
                mc.player != null &&
                mc.player.getMainHandItem().getItem().isEdible()
            ) {
                return "[Right-click] Feed";
            }
            ItemStack gag = state.getEquipment(BodyRegionV2.MOUTH);
            if (state.isLocked(gag, false)) {
                return struggleKey + " Help struggle";
            }
            return "[Right-click] Remove gag";
        }

        if (state.isBlindfolded()) {
            ItemStack blindfold = state.getEquipment(BodyRegionV2.EYES);
            if (state.isLocked(blindfold, false)) {
                return struggleKey + " Help struggle";
            }
            return "[Right-click] Remove blindfold";
        }

        if (state.hasCollar()) {
            ItemStack collar = state.getEquipment(BodyRegionV2.NECK);
            if (state.isLocked(collar, false)) {
                return struggleKey + " Help struggle";
            }
            return "[Right-click] Remove collar";
        }

        if (state.hasEarplugs()) {
            ItemStack earplugs = state.getEquipment(BodyRegionV2.EARS);
            if (state.isLocked(earplugs, false)) {
                return struggleKey + " Help struggle";
            }
            return "[Right-click] Remove earplugs";
        }

        if (state.hasMittens()) {
            ItemStack mittens = state.getEquipment(BodyRegionV2.HANDS);
            if (state.isLocked(mittens, false)) {
                return struggleKey + " Help struggle";
            }
            return "[Right-click] Remove mittens";
        }

        return null;
    }
}
