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

import com.tiedup.remake.client.gui.util.GuiRenderUtil;
import com.tiedup.remake.v2.BodyRegionV2;
import com.tiedup.remake.v2.bondage.capability.V2EquipmentHelper;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.Consumer;
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.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Tab bar for the unified bondage screen. 5 body-zone tabs with occupied indicators.
 */
@OnlyIn(Dist.CLIENT)
public class RegionTabBar extends AbstractWidget {

    /**
     * Body zone tabs grouping the 14 BodyRegionV2 values.
     */
    public enum BodyTab {
        HEAD(
            "gui.tiedup.tab.head",
            BodyRegionV2.HEAD,
            BodyRegionV2.EYES,
            BodyRegionV2.EARS,
            BodyRegionV2.MOUTH
        ),
        UPPER("gui.tiedup.tab.upper", BodyRegionV2.NECK, BodyRegionV2.TORSO),
        ARMS(
            "gui.tiedup.tab.arms",
            BodyRegionV2.ARMS,
            BodyRegionV2.HANDS,
            BodyRegionV2.FINGERS
        ),
        LOWER(
            "gui.tiedup.tab.lower",
            BodyRegionV2.WAIST,
            BodyRegionV2.LEGS,
            BodyRegionV2.FEET
        ),
        SPECIAL(
            "gui.tiedup.tab.special",
            BodyRegionV2.TAIL,
            BodyRegionV2.WINGS
        );

        private final String translationKey;
        private final Set<BodyRegionV2> regions;

        BodyTab(String translationKey, BodyRegionV2... regions) {
            this.translationKey = translationKey;
            this.regions = EnumSet.noneOf(BodyRegionV2.class);
            for (BodyRegionV2 r : regions) this.regions.add(r);
        }

        public String getTranslationKey() {
            return translationKey;
        }

        public Set<BodyRegionV2> getRegions() {
            return regions;
        }

        /** Check if any region in this tab has an equipped item on the entity. */
        public boolean hasEquippedItems(LivingEntity entity) {
            for (BodyRegionV2 region : regions) {
                if (
                    V2EquipmentHelper.isRegionOccupied(entity, region)
                ) return true;
            }
            return false;
        }
    }

    // Visual constants
    private static final int TAB_HEIGHT = 26;
    private static final int TAB_SPACING = 4;
    private static final int DOT_RADIUS = 3;

    // Colors (vanilla MC style)
    private static final int BG_ACTIVE = 0xFFC6C6C6; // Same as main panel
    private static final int BG_INACTIVE = 0xFF8B8B8B; // Darker, slot-like
    private static final int BG_HOVER = 0xFFA0A0A0; // Between active and inactive
    private static final int TEXT_ACTIVE = 0xFF404040; // Dark text
    private static final int TEXT_INACTIVE = 0xFF555555; // Gray text
    private static final int BAR_BG = 0xFFA0A0A0;

    private BodyTab activeTab = BodyTab.HEAD;
    private Consumer<BodyTab> onTabChanged;
    private LivingEntity targetEntity;

    public RegionTabBar(int x, int y, int width) {
        super(x, y, width, TAB_HEIGHT, Component.translatable("gui.tiedup.tab_bar.label"));
    }

    public void setOnTabChanged(Consumer<BodyTab> callback) {
        this.onTabChanged = callback;
    }

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

    public BodyTab getActiveTab() {
        return activeTab;
    }

    public void setActiveTab(BodyTab tab) {
        if (this.activeTab != tab) {
            this.activeTab = tab;
            if (onTabChanged != null) onTabChanged.accept(tab);
        }
    }

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

        // Background bar
        graphics.fill(getX(), getY(), getX() + width, getY() + height, BAR_BG);

        BodyTab[] tabs = BodyTab.values();
        int tabWidth = (width - TAB_SPACING * (tabs.length - 1)) / tabs.length;

        for (int i = 0; i < tabs.length; i++) {
            BodyTab tab = tabs[i];
            int tabX = getX() + i * (tabWidth + TAB_SPACING);
            boolean isActive = (tab == activeTab);
            boolean isHovered =
                mouseX >= tabX &&
                mouseX < tabX + tabWidth &&
                mouseY >= getY() &&
                mouseY < getY() + height;

            int bgColor = isActive
                ? BG_ACTIVE
                : (isHovered ? BG_HOVER : BG_INACTIVE);
            graphics.fill(
                tabX,
                getY(),
                tabX + tabWidth,
                getY() + height,
                bgColor
            );

            if (isActive) {
                // Active tab: raised 3D look, no bottom border (connects to panel below)
                // Top highlight
                graphics.fill(
                    tabX,
                    getY(),
                    tabX + tabWidth,
                    getY() + 1,
                    GuiRenderUtil.MC_HIGHLIGHT_OUTER
                );
                // Left highlight
                graphics.fill(
                    tabX,
                    getY(),
                    tabX + 1,
                    getY() + height,
                    GuiRenderUtil.MC_HIGHLIGHT_OUTER
                );
                // Right shadow
                graphics.fill(
                    tabX + tabWidth - 1,
                    getY(),
                    tabX + tabWidth,
                    getY() + height,
                    GuiRenderUtil.MC_SHADOW_OUTER
                );
            } else {
                // Inactive tab: full 3D sunken borders
                // Top shadow
                graphics.fill(
                    tabX,
                    getY(),
                    tabX + tabWidth,
                    getY() + 1,
                    GuiRenderUtil.MC_SHADOW_OUTER
                );
                // Left shadow
                graphics.fill(
                    tabX,
                    getY(),
                    tabX + 1,
                    getY() + height,
                    GuiRenderUtil.MC_SHADOW_OUTER
                );
                // Bottom highlight
                graphics.fill(
                    tabX,
                    getY() + height - 1,
                    tabX + tabWidth,
                    getY() + height,
                    GuiRenderUtil.MC_HIGHLIGHT_OUTER
                );
                // Right highlight
                graphics.fill(
                    tabX + tabWidth - 1,
                    getY(),
                    tabX + tabWidth,
                    getY() + height,
                    GuiRenderUtil.MC_HIGHLIGHT_OUTER
                );
            }

            // Tab label
            String label = Component.translatable(
                tab.getTranslationKey()
            ).getString();
            int textColor = isActive ? TEXT_ACTIVE : TEXT_INACTIVE;
            int textX = tabX + (tabWidth - mc.font.width(label)) / 2;
            int textY = getY() + (height - mc.font.lineHeight) / 2;
            graphics.drawString(mc.font, label, textX, textY, textColor, false);

            // Occupied dot indicator (top-right corner of tab) — white/light gray
            if (targetEntity != null && tab.hasEquippedItems(targetEntity)) {
                int dotX = tabX + tabWidth - DOT_RADIUS - 4;
                int dotY = getY() + 4;
                graphics.fill(
                    dotX - DOT_RADIUS,
                    dotY - DOT_RADIUS,
                    dotX + DOT_RADIUS,
                    dotY + DOT_RADIUS,
                    0xFFCCCCCC
                );
            }
        }
    }

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

        BodyTab[] tabs = BodyTab.values();
        int tabWidth = (width - TAB_SPACING * (tabs.length - 1)) / tabs.length;

        for (int i = 0; i < tabs.length; i++) {
            int tabX = getX() + i * (tabWidth + TAB_SPACING);
            if (mouseX >= tabX && mouseX < tabX + tabWidth) {
                setActiveTab(tabs[i]);
                playDownSound(Minecraft.getInstance().getSoundManager());
                return true;
            }
        }
        return false;
    }

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