package com.tiedup.remake.network.minigame;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.items.ItemLockpick;
import com.tiedup.remake.items.base.ILockable;
import com.tiedup.remake.minigame.LockpickMiniGameState;
import com.tiedup.remake.minigame.LockpickSessionManager;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.PacketRateLimiter;
import com.tiedup.remake.state.PlayerBindState;
import com.tiedup.remake.v2.BodyRegionV2;
import com.tiedup.remake.v2.bondage.capability.V2EquipmentHelper;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.network.NetworkEvent;

/**
 *
 * Sent when player clicks "Lockpick" on a locked item.
 */
public class PacketLockpickMiniGameStart {

    private final BodyRegionV2 targetRegion;

    public PacketLockpickMiniGameStart(BodyRegionV2 targetRegion) {
        this.targetRegion = targetRegion;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeEnum(targetRegion);
    }

    public static PacketLockpickMiniGameStart decode(FriendlyByteBuf buf) {
        return new PacketLockpickMiniGameStart(
            buf.readEnum(BodyRegionV2.class)
        );
    }

    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;

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

        // Check for mittens
        if (state.hasMittens()) {
            TiedUpMod.LOGGER.debug(
                "[PacketLockpickMiniGameStart] Player {} has mittens, cannot lockpick",
                player.getName().getString()
            );
            return;
        }

        // Find lockpick in inventory
        ItemStack lockpickStack = ItemLockpick.findLockpickInInventory(player);
        if (lockpickStack.isEmpty()) {
            TiedUpMod.LOGGER.debug(
                "[PacketLockpickMiniGameStart] Player {} has no lockpick",
                player.getName().getString()
            );
            return;
        }

        // Get target item via V2 equipment system
        ItemStack targetStack = V2EquipmentHelper.getInRegion(
            player,
            targetRegion
        );

        if (
            targetStack.isEmpty() ||
            !(targetStack.getItem() instanceof ILockable lockable)
        ) {
            TiedUpMod.LOGGER.debug(
                "[PacketLockpickMiniGameStart] Target region {} is not lockable",
                targetRegion
            );
            return;
        }

        if (!lockable.isLocked(targetStack)) {
            TiedUpMod.LOGGER.debug(
                "[PacketLockpickMiniGameStart] Target region {} is not locked",
                targetRegion
            );
            return;
        }

        if (lockable.isJammed(targetStack)) {
            TiedUpMod.LOGGER.debug(
                "[PacketLockpickMiniGameStart] Target region {} is jammed",
                targetRegion
            );
            return;
        }

        // Determine sweet spot width based on lockpick type
        float sweetSpotWidth = 0.03f; // 3% - Very difficult sweet spot (Skyrim-style)

        // Get remaining uses
        int remainingUses =
            lockpickStack.getMaxDamage() - lockpickStack.getDamageValue();

        // Start session
        LockpickSessionManager manager = LockpickSessionManager.getInstance();
        LockpickMiniGameState session = manager.startLockpickSession(
            player,
            com.tiedup.remake.minigame.LockpickTargetKind.BODY_REGION,
            targetRegion.ordinal(),
            sweetSpotWidth
        );

        if (session == null) {
            TiedUpMod.LOGGER.warn(
                "[PacketLockpickMiniGameStart] Failed to create lockpick session for {}",
                player.getName().getString()
            );
            return;
        }

        session.setRemainingUses(remainingUses);

        TiedUpMod.LOGGER.info(
            "[PacketLockpickMiniGameStart] Started lockpick session for {} (region: {}, uses: {})",
            player.getName().getString(),
            targetRegion,
            remainingUses
        );

        // Send initial state to client
        ModNetwork.sendToPlayer(
            new PacketLockpickMiniGameState(
                session.getSessionId(),
                session.getSweetSpotCenter(),
                session.getSweetSpotWidth(),
                session.getCurrentPosition(),
                session.getRemainingUses()
            ),
            player
        );
    }
}
