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

import com.tiedup.remake.client.gui.util.GuiColors;
import com.tiedup.remake.client.gui.util.GuiRenderUtil;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.tasks.PlayerStateTask;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Player;
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 progress bar for tying/untying/struggling actions.
 * Displayed above the hotbar when an action is in progress.
 *
 */
@OnlyIn(Dist.CLIENT)
@Mod.EventBusSubscriber(modid = TiedUpMod.MOD_ID, value = Dist.CLIENT)
public class ProgressOverlay {

    // Bar dimensions
    private static final int BAR_WIDTH = 200;
    private static final int BAR_HEIGHT = 12;
    private static final int PADDING = 4;

    // Animation
    private static float smoothProgress = 0.0f;
    private static final float SMOOTH_SPEED = 0.15f;

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

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

        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) {
            return;
        }

        // Check for active actions
        ProgressInfo info = getActiveProgress(state);
        if (info == null) {
            // Fade out smoothly
            smoothProgress = Math.max(0, smoothProgress - SMOOTH_SPEED);
            if (smoothProgress <= 0.01f) {
                return;
            }
        } else {
            // Smooth interpolation
            smoothProgress += (info.progress - smoothProgress) * SMOOTH_SPEED;
        }

        if (info == null && smoothProgress <= 0.01f) {
            return;
        }

        GuiGraphics graphics = event.getGuiGraphics();
        int screenWidth = mc.getWindow().getGuiScaledWidth();
        int screenHeight = mc.getWindow().getGuiScaledHeight();

        // Center horizontally, above hotbar
        int x = (screenWidth - BAR_WIDTH) / 2;
        int y = screenHeight - 60;

        // Background panel
        int panelHeight = BAR_HEIGHT + PADDING * 2 + 12; // +12 for text
        graphics.fill(
            x - PADDING,
            y - PADDING,
            x + BAR_WIDTH + PADDING,
            y + panelHeight,
            GuiColors.withAlpha(GuiColors.BG_DARK, 200)
        );

        // Progress bar background
        graphics.fill(x, y, x + BAR_WIDTH, y + BAR_HEIGHT, GuiColors.BG_LIGHT);

        // Progress bar fill
        int fillWidth = (int) (BAR_WIDTH * smoothProgress);
        int fillColor = info != null ? info.color : GuiColors.ACCENT_TAN;
        graphics.fill(x, y, x + fillWidth, y + BAR_HEIGHT, fillColor);

        // Border
        GuiRenderUtil.drawBorder(
            graphics,
            x,
            y,
            BAR_WIDTH,
            BAR_HEIGHT,
            GuiColors.BORDER_LIGHT
        );

        // Percentage text
        String percent = String.format("%.0f%%", smoothProgress * 100);
        int textWidth = mc.font.width(percent);
        graphics.drawString(
            mc.font,
            percent,
            x + (BAR_WIDTH - textWidth) / 2,
            y + (BAR_HEIGHT - mc.font.lineHeight) / 2 + 1,
            GuiColors.TEXT_WHITE,
            false
        );

        // Description text
        if (info != null) {
            graphics.drawCenteredString(
                mc.font,
                info.description,
                x + BAR_WIDTH / 2,
                y + BAR_HEIGHT + PADDING,
                GuiColors.TEXT_GRAY
            );
        }
    }

    /**
     * Get active progress information.
     */
    private static ProgressInfo getActiveProgress(PlayerBindState state) {
        // Check client tying task
        PlayerStateTask tyingTask = state.tasks().getClientTyingTask();
        if (tyingTask != null && !tyingTask.isOutdated()) {
            float progress = tyingTask.getProgress();
            Component text = getTyingText(tyingTask);
            return new ProgressInfo(progress, GuiColors.WARNING, text);
        }

        // Check client untying task
        PlayerStateTask untyingTask = state.tasks().getClientUntyingTask();
        if (untyingTask != null && !untyingTask.isOutdated()) {
            float progress = untyingTask.getProgress();
            Component text = getUntyingText(untyingTask);
            return new ProgressInfo(progress, GuiColors.SUCCESS, text);
        }

        // Check client feeding task
        PlayerStateTask feedingTask = state.tasks().getClientFeedingTask();
        if (feedingTask != null && !feedingTask.isOutdated()) {
            float progress = feedingTask.getProgress();
            Component text = getFeedingText(feedingTask);
            return new ProgressInfo(progress, GuiColors.ACCENT_TAN, text);
        }

        return null;
    }

    /**
     * Get the appropriate text for tying progress based on role.
     */
    private static Component getTyingText(PlayerStateTask task) {
        String otherName = task.getOtherEntityName();
        if (otherName == null || otherName.isEmpty()) {
            otherName = "???";
        }

        if (task.isKidnapper()) {
            // Kidnapper sees: "Tying [target]..."
            return Component.translatable(
                "gui.tiedup.action.tying_target",
                otherName
            );
        } else {
            // Victim sees: "[kidnapper] is tying you up!"
            return Component.translatable(
                "gui.tiedup.action.being_tied_by",
                otherName
            );
        }
    }

    /**
     * Get the appropriate text for untying progress based on role.
     */
    private static Component getUntyingText(PlayerStateTask task) {
        String otherName = task.getOtherEntityName();
        if (otherName == null || otherName.isEmpty()) {
            otherName = "???";
        }

        if (task.isKidnapper()) {
            // Helper sees: "Untying [target]..."
            return Component.translatable(
                "gui.tiedup.action.untying_target",
                otherName
            );
        } else {
            // Victim sees: "[helper] is untying you!"
            return Component.translatable(
                "gui.tiedup.action.being_untied_by",
                otherName
            );
        }
    }

    /**
     * Get the appropriate text for feeding progress based on role.
     */
    private static Component getFeedingText(PlayerStateTask task) {
        String otherName = task.getOtherEntityName();
        if (otherName == null || otherName.isEmpty()) {
            otherName = "???";
        }

        if (task.isKidnapper()) {
            // Feeder sees: "Feeding [target]..."
            return Component.translatable(
                "gui.tiedup.action.feeding_target",
                otherName
            );
        } else {
            // Target sees: "[feeder] is feeding you!"
            return Component.translatable(
                "gui.tiedup.action.being_fed_by",
                otherName
            );
        }
    }

    /**
     * Progress information container.
     */
    private static class ProgressInfo {

        final float progress;
        final int color;
        final Component description;

        ProgressInfo(float progress, int color, Component description) {
            this.progress = progress;
            this.color = color;
            this.description = description;
        }
    }
}
