package com.tiedup.remake.network.minigame;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.minigame.ContinuousStruggleMiniGameState;
import com.tiedup.remake.minigame.StruggleSessionManager;
import com.tiedup.remake.network.PacketRateLimiter;
import com.tiedup.remake.network.sync.SyncManager;
import com.tiedup.remake.state.PlayerBindState;
import java.util.UUID;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;

/**
 * Client to Server packet to stop the continuous struggle session.
 *
 * Sent when:
 * - Player presses ESC to close the screen
 * - Player takes damage (detected client-side)
 */
public class PacketContinuousStruggleStop {

    private final UUID sessionId;

    public PacketContinuousStruggleStop(UUID sessionId) {
        this.sessionId = sessionId;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeUUID(sessionId);
    }

    public static PacketContinuousStruggleStop decode(FriendlyByteBuf buf) {
        UUID sessionId = buf.readUUID();
        return new PacketContinuousStruggleStop(sessionId);
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                ServerPlayer player = ctx.get().getSender();
                if (player == null) {
                    return;
                }
                handleServer(player);
            });
        ctx.get().setPacketHandled(true);
    }

    private void handleServer(ServerPlayer player) {
        if (!PacketRateLimiter.allowPacket(player, "minigame")) return;

        StruggleSessionManager manager = StruggleSessionManager.getInstance();
        ContinuousStruggleMiniGameState session =
            manager.getContinuousStruggleSession(player.getUUID());

        if (session == null) {
            TiedUpMod.LOGGER.debug(
                "[PacketContinuousStruggleStop] No active session for {}",
                player.getName().getString()
            );
            return;
        }

        // Validate session ID
        if (!session.getSessionId().equals(sessionId)) {
            TiedUpMod.LOGGER.debug(
                "[PacketContinuousStruggleStop] Session ID mismatch for {}",
                player.getName().getString()
            );
            return;
        }

        TiedUpMod.LOGGER.info(
            "[PacketContinuousStruggleStop] Player {} stopped struggle session",
            player.getName().getString()
        );

        // Cancel the session
        session.cancel();

        // Clear struggle animation state and sync
        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state != null) {
            state.setStruggling(false, 0);
            SyncManager.syncStruggleState(player);
        }

        // End the session in the manager
        manager.endContinuousStruggleSession(player.getUUID(), false);
    }

    // Getter
    public UUID getSessionId() {
        return sessionId;
    }
}
