package de.winniepat.citrus.draggui;

import io.wispforest.owo.ui.component.Components;
import io.wispforest.owo.ui.container.Containers;
import io.wispforest.owo.ui.container.FlowLayout;
import io.wispforest.owo.ui.core.*;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;

import java.util.function.Consumer;

public class HudUtils {
    public static Component createButton(String label, String texture, String tooltip, boolean initialState, Consumer<Boolean> onToggle) {
        var textureComponent = Components.texture(Identifier.of("citrus", "textures/modules/" + texture + ".png"), 0, 0, 48, 48, 48, 48);

        var wrapper = Containers.verticalFlow(Sizing.content(), Sizing.content());
        wrapper.child(textureComponent);
        wrapper.padding(Insets.of(2));

        wrapper.mouseDown().subscribe((x, y, b) -> {
            if (b != 0) return false;
            boolean newState = !HudConfig.INSTANCE.isModuleEnabled(label);
            onToggle.accept(newState);
            updateWrapperVisuals(wrapper, newState);
            HudConfig.save();
            return true;
        });

        wrapper.tooltip(Text.literal(tooltip));
        wrapper.cursorStyle(CursorStyle.HAND);
        updateWrapperVisuals(wrapper, initialState);
        return wrapper;
    }

    private static void updateWrapperVisuals(FlowLayout wrapper, boolean enabled) {
        int color = enabled ? Color.ofArgb(0xFF00FF00).argb() : Color.ofArgb(0xFFFF0000).argb();
        wrapper.surface((context, component) -> {
            int x = component.x();
            int y = component.y();
            int w = component.width();
            int h = component.height();

            context.fill(x + 4, y, x + w - 4, y + 1, color);
            context.fill(x + 4, y + h - 1, x + w - 4, y + h, color);
            context.fill(x, y + 4, x + 1, y + h - 4, color);
            context.fill(x + w - 1, y + 4, x + w, y + h - 4, color);

            context.fill(x + 2, y + 1, x + 4, y + 2, color);
            context.fill(x + 1, y + 2, x + 2, y + 4, color);

            context.fill(x + w - 4, y + 1, x + w - 2, y + 2, color);
            context.fill(x + w - 2, y + 2, x + w - 1, y + 4, color);

            context.fill(x + 2, y + h - 2, x + 4, y + h - 1, color);
            context.fill(x + 1, y + h - 4, x + 2, y + h - 2, color);

            context.fill(x + w - 4, y + h - 2, x + w - 2, y + h - 1, color);
            context.fill(x + w - 2, y + h - 4, x + w - 1, y + h - 2, color);
        });
    }
}