package com.tiedup.remake.compat.mca.network;

import com.tiedup.remake.compat.mca.MCACompat;
import com.tiedup.remake.compat.mca.capability.MCAKidnappedCapability;
import com.tiedup.remake.core.TiedUpMod;
import java.util.function.Supplier;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet to sync MCA villager bondage state from server to client.
 *
 * Sent when bondage items are added/removed from MCA villagers.
 * Contains all 7 bondage slots for the entity.
 */
public class PacketSyncMCABondage {

    private final int entityId;
    private final ItemStack bind;
    private final ItemStack gag;
    private final ItemStack blindfold;
    private final ItemStack earplugs;
    private final ItemStack collar;
    private final ItemStack clothes;
    private final ItemStack mittens;

    public PacketSyncMCABondage(
        int entityId,
        ItemStack bind,
        ItemStack gag,
        ItemStack blindfold,
        ItemStack earplugs,
        ItemStack collar,
        ItemStack clothes,
        ItemStack mittens
    ) {
        this.entityId = entityId;
        this.bind = bind;
        this.gag = gag;
        this.blindfold = blindfold;
        this.earplugs = earplugs;
        this.collar = collar;
        this.clothes = clothes;
        this.mittens = mittens;
    }

    /**
     * Create packet from MCA villager's capability.
     */
    public static PacketSyncMCABondage fromEntity(
        Entity entity,
        MCAKidnappedCapability cap
    ) {
        return new PacketSyncMCABondage(
            entity.getId(),
            cap.getBind(),
            cap.getGag(),
            cap.getBlindfold(),
            cap.getEarplugs(),
            cap.getCollar(),
            cap.getClothes(),
            cap.getMittens()
        );
    }

    /**
     * Decode packet from network buffer.
     */
    public static PacketSyncMCABondage decode(FriendlyByteBuf buf) {
        int entityId = buf.readVarInt();
        ItemStack bind = buf.readItem();
        ItemStack gag = buf.readItem();
        ItemStack blindfold = buf.readItem();
        ItemStack earplugs = buf.readItem();
        ItemStack collar = buf.readItem();
        ItemStack clothes = buf.readItem();
        ItemStack mittens = buf.readItem();
        return new PacketSyncMCABondage(
            entityId,
            bind,
            gag,
            blindfold,
            earplugs,
            collar,
            clothes,
            mittens
        );
    }

    /**
     * Encode packet to network buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeVarInt(entityId);
        buf.writeItem(bind);
        buf.writeItem(gag);
        buf.writeItem(blindfold);
        buf.writeItem(earplugs);
        buf.writeItem(collar);
        buf.writeItem(clothes);
        buf.writeItem(mittens);
    }

    /**
     * Handle packet on client side.
     */
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> handleClient());
        ctx.get().setPacketHandled(true);
    }

    @OnlyIn(Dist.CLIENT)
    private void handleClient() {
        Minecraft mc = Minecraft.getInstance();
        if (mc.level == null) return;

        Entity entity = mc.level.getEntity(entityId);
        if (entity == null) {
            TiedUpMod.LOGGER.debug(
                "[MCA Sync] Entity {} not found on client",
                entityId
            );
            return;
        }

        // Get the capability and update it
        entity
            .getCapability(MCACompat.MCA_KIDNAPPED)
            .ifPresent(cap -> {
                cap.setBind(bind);
                cap.setGag(gag);
                cap.setBlindfold(blindfold);
                cap.setEarplugs(earplugs);
                cap.setCollar(collar);
                cap.setClothes(clothes);
                cap.setMittens(mittens);

                TiedUpMod.LOGGER.debug(
                    "[MCA Sync] Updated bondage for {} (bind: {})",
                    entity.getName().getString(),
                    !bind.isEmpty()
                        ? bind.getItem().getClass().getSimpleName()
                        : "none"
                );
            });
    }
}
