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

import com.tiedup.remake.client.gui.util.GuiColors;
import com.tiedup.remake.client.gui.util.GuiRenderUtil;
import com.tiedup.remake.items.GenericKnife;
import com.tiedup.remake.items.ItemKey;
import com.tiedup.remake.items.ItemLockpick;
import com.tiedup.remake.items.ModItems;
import com.tiedup.remake.items.base.IHasResistance;
import com.tiedup.remake.v2.BodyRegionV2;
import com.tiedup.remake.v2.bondage.capability.V2EquipmentHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarratedElementType;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Bottom status bar for the unified bondage screen.
 * Self mode: tool status + resistance info.
 * Master mode: key info + target info.
 */
@OnlyIn(Dist.CLIENT)
public class StatusBarWidget extends AbstractWidget {

    private static final int PADDING = 8;

    private ActionPanel.ScreenMode mode = ActionPanel.ScreenMode.SELF;
    private LivingEntity targetEntity;
    private Runnable onCloseClicked;

    // Close button layout
    private static final int CLOSE_BTN_WIDTH = 100;
    private static final int CLOSE_BTN_HEIGHT = 22;

    public StatusBarWidget(int x, int y, int width, int height) {
        super(x, y, width, height, Component.translatable("gui.tiedup.status_bar"));
    }

    public void setMode(ActionPanel.ScreenMode mode) {
        this.mode = mode;
    }

    public void setTargetEntity(LivingEntity entity) {
        this.targetEntity = entity;
    }

    public void setOnCloseClicked(Runnable cb) {
        this.onCloseClicked = cb;
    }

    @Override
    protected void renderWidget(
        GuiGraphics graphics,
        int mouseX,
        int mouseY,
        float partialTick
    ) {
        Minecraft mc = Minecraft.getInstance();
        Player player = mc.player;
        if (player == null) return;

        // MC-style sunken inset panel (slightly darker than main)
        GuiRenderUtil.drawMCSunkenPanel(
            graphics,
            getX(),
            getY(),
            width,
            height
        );

        int textY1 = getY() + PADDING;
        int textY2 = textY1 + mc.font.lineHeight + 2;

        if (mode == ActionPanel.ScreenMode.SELF) {
            renderSelfStatus(graphics, player, textY1, textY2);
        } else {
            renderMasterStatus(graphics, player, textY1, textY2);
        }

        // Close button (right side, MC-style button)
        int closeBtnX = getX() + width - CLOSE_BTN_WIDTH - PADDING;
        int closeBtnY = getY() + (height - CLOSE_BTN_HEIGHT) / 2;
        boolean closeHovered =
            mouseX >= closeBtnX &&
            mouseX < closeBtnX + CLOSE_BTN_WIDTH &&
            mouseY >= closeBtnY &&
            mouseY < closeBtnY + CLOSE_BTN_HEIGHT;
        GuiRenderUtil.drawMCButton(
            graphics,
            closeBtnX,
            closeBtnY,
            CLOSE_BTN_WIDTH,
            CLOSE_BTN_HEIGHT,
            closeHovered,
            true
        );
        String closeText = Component.translatable(
            "gui.tiedup.close_esc"
        ).getString();
        GuiRenderUtil.drawCenteredStringNoShadow(
            graphics,
            mc.font,
            closeText,
            closeBtnX + CLOSE_BTN_WIDTH / 2,
            closeBtnY + (CLOSE_BTN_HEIGHT - mc.font.lineHeight) / 2,
            GuiRenderUtil.MC_TEXT_DARK
        );
    }

    private void renderSelfStatus(
        GuiGraphics graphics,
        Player player,
        int y1,
        int y2
    ) {
        Minecraft mc = Minecraft.getInstance();
        int x = getX() + PADDING;

        // Tool status line 1
        ItemStack lockpick = ItemLockpick.findLockpickInInventory(player);
        String pickText = lockpick.isEmpty()
            ? Component.translatable(
                  "gui.tiedup.status.no_lockpick"
              ).getString()
            : Component.translatable(
                  "gui.tiedup.status.lockpick_uses",
                  lockpick.getMaxDamage() - lockpick.getDamageValue()
              ).getString();
        graphics.drawString(
            mc.font,
            pickText,
            x,
            y1,
            GuiRenderUtil.MC_TEXT_DARK,
            false
        );

        ItemStack knife = GenericKnife.findKnifeInInventory(player);
        String knifeText = knife.isEmpty()
            ? Component.translatable("gui.tiedup.status.no_knife").getString()
            : Component.translatable(
                  "gui.tiedup.status.knife_uses",
                  knife.getMaxDamage() - knife.getDamageValue()
              ).getString();
        graphics.drawString(
            mc.font,
            knifeText,
            x + 150,
            y1,
            GuiRenderUtil.MC_TEXT_DARK,
            false
        );

        // Arms resistance line 2
        ItemStack armsBind = V2EquipmentHelper.getInRegion(
            player,
            BodyRegionV2.ARMS
        );
        if (
            !armsBind.isEmpty() &&
            armsBind.getItem() instanceof IHasResistance res
        ) {
            int curr = res.getCurrentResistance(armsBind, player);
            int max = res.getBaseResistance(player);
            String resText = Component.translatable(
                "gui.tiedup.status.arms_resistance",
                curr,
                max
            ).getString();
            int color = curr < max * 0.3 ? GuiColors.ERROR : GuiColors.SUCCESS;
            graphics.drawString(mc.font, resText, x, y2, color, false);
        }
    }

    private void renderMasterStatus(
        GuiGraphics graphics,
        Player player,
        int y1,
        int y2
    ) {
        Minecraft mc = Minecraft.getInstance();
        int x = getX() + PADDING;

        // Key info — check for ItemKey first, then master key as fallback
        ItemStack keyStack = ItemStack.EMPTY;
        for (int i = 0; i < player.getInventory().getContainerSize(); i++) {
            ItemStack stack = player.getInventory().getItem(i);
            if (stack.isEmpty()) continue;
            if (stack.getItem() instanceof ItemKey) {
                keyStack = stack;
                break; // Regular key takes priority
            }
            if (keyStack.isEmpty() && stack.is(ModItems.MASTER_KEY.get())) {
                keyStack = stack; // Remember master key as fallback, keep scanning
            }
        }

        String keyText;
        if (keyStack.isEmpty()) {
            keyText = Component.translatable(
                "gui.tiedup.status.no_key"
            ).getString();
        } else {
            keyText = Component.translatable(
                "gui.tiedup.status.key_info",
                keyStack.getHoverName().getString()
            ).getString();
        }
        graphics.drawString(
            mc.font,
            keyText,
            x,
            y1,
            GuiRenderUtil.MC_TEXT_DARK,
            false
        );

        // Target info
        if (targetEntity != null) {
            String targetText = Component.translatable(
                "gui.tiedup.status.target_info",
                targetEntity.getName().getString()
            ).getString();
            graphics.drawString(
                mc.font,
                targetText,
                x,
                y2,
                GuiRenderUtil.MC_TEXT_DARK,
                false
            );
        }
    }

    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {
        if (!isMouseOver(mouseX, mouseY) || button != 0) return false;

        int closeBtnX = getX() + width - CLOSE_BTN_WIDTH - PADDING;
        int closeBtnY = getY() + (height - CLOSE_BTN_HEIGHT) / 2;
        if (
            mouseX >= closeBtnX &&
            mouseX < closeBtnX + CLOSE_BTN_WIDTH &&
            mouseY >= closeBtnY &&
            mouseY < closeBtnY + CLOSE_BTN_HEIGHT
        ) {
            if (onCloseClicked != null) onCloseClicked.run();
            playDownSound(Minecraft.getInstance().getSoundManager());
            return true;
        }
        return false;
    }

    @Override
    protected void updateWidgetNarration(NarrationElementOutput output) {
        output.add(
            NarratedElementType.TITLE,
            Component.translatable("gui.tiedup.status_bar")
        );
    }
}
