package wtf.opal.client.renderer.component;

import com.ibm.icu.impl.Pair;
import java.util.function.BooleanSupplier;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import wtf.opal.client.renderer.NVGRenderer;
import wtf.opal.utility.misc.HoverUtility;
import wtf.opal.utility.render.ColorUtility;
import wtf.opal.utility.render.ScreenPosition;
import wtf.opal.utility.render.animation.Animation;
import wtf.opal.utility.render.animation.Easing;

@Environment(EnvType.CLIENT)
public final class ToggleSwitchComponent extends ScreenPosition {
   private Animation toggleAnimation;
   private final Runnable toggleAction;
   private final BooleanSupplier stateSupplier;
   private Pair<Integer, Integer> boxColors;

   public ToggleSwitchComponent(Runnable toggleAction, BooleanSupplier stateSupplier) {
      this.toggleAction = toggleAction;
      this.stateSupplier = stateSupplier;
   }

   public void reset() {
      this.toggleAnimation = null;
   }

   public void render(float x, float y, float scale) {
      this.x = x;
      this.y = y;
      this.width = 20.0F;
      this.height = 10.0F;
      NVGRenderer.scale(
         scale,
         x,
         y,
         this.width,
         this.height,
         () -> {
            float var3 = this.stateSupplier.getAsBoolean() ? 1.0F : 0.0F;
            if (this.toggleAnimation == null) {
               this.toggleAnimation = new Animation(Easing.DECELERATE, 150L);
               this.toggleAnimation.setValue(var3);
            } else {
               this.toggleAnimation.run(var3);
            }

            Pair var4 = this.boxColors == null ? Pair.of(ColorUtility.getToggleFillColor(), ColorUtility.getToggleBackgroundColor()) : this.boxColors;
            int var5 = ColorUtility.interpolateColors((Integer)var4.second, (Integer)var4.first, this.toggleAnimation.getValue());
            NVGRenderer.roundedRect(x, y, this.width, this.height, this.height / 2.0F, var5);
            NVGRenderer.roundedRect(
               x + 1.0F + this.toggleAnimation.getValue() * 9.5F,
               y + 1.0F,
               this.height - 2.0F,
               this.height - 2.0F,
               (this.height - 2.0F) / 2.0F,
               ColorUtility.getToggleCircleColor()
            );
         }
      );
   }

   public void setBoxColors(Pair<Integer, Integer> boxColors) {
      this.boxColors = boxColors;
   }

   public void mouseClicked(double mouseX, double mouseY, float scale) {
      if (HoverUtility.isHovering(this.x, this.y, this.width, this.height, mouseX, mouseY, scale)) {
         this.toggle();
      }
   }

   public void mouseClicked(float x, float y, float width, float height, double mouseX, double mouseY) {
      if (HoverUtility.isHovering(x, y, width, height, mouseX, mouseY)) {
         this.toggle();
      }
   }

   public void toggle() {
      if (this.toggleAction != null) {
         this.toggleAction.run();
      }
   }
}
