package com.tiedup.remake.network.merchant;

import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.entities.MerchantTrade;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent;

/**
 * Packet sent from server to client to open the merchant trading screen.
 *
 * Contains:
 * - Merchant entity ID
 * - List of available trades
 */
public class PacketOpenMerchantScreen {

    private final UUID merchantUUID;
    private final List<MerchantTrade> trades;

    /**
     * Create packet to open merchant screen.
     *
     * @param merchantUUID The UUID of the merchant entity (persistent across restarts)
     * @param trades List of available trades
     */
    public PacketOpenMerchantScreen(
        UUID merchantUUID,
        List<MerchantTrade> trades
    ) {
        this.merchantUUID = merchantUUID;
        this.trades = new ArrayList<>(trades);
    }

    /**
     * Encode the packet to the network buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        buf.writeUUID(merchantUUID);
        buf.writeInt(trades.size());
        for (MerchantTrade trade : trades) {
            buf.writeNbt(trade.save());
        }
    }

    /**
     * Decode the packet from the network buffer.
     */
    public static PacketOpenMerchantScreen decode(FriendlyByteBuf buf) {
        UUID uuid = buf.readUUID();
        int tradeCount = buf.readInt();
        List<MerchantTrade> trades = new ArrayList<>();

        for (int i = 0; i < tradeCount; i++) {
            CompoundTag tag = buf.readNbt();
            if (tag != null) {
                trades.add(MerchantTrade.load(tag));
            }
        }

        return new PacketOpenMerchantScreen(uuid, trades);
    }

    /**
     * Handle the packet on the receiving side (CLIENT SIDE).
     */
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx
            .get()
            .enqueueWork(() -> {
                if (FMLEnvironment.dist == Dist.CLIENT) {
                    handleClient();
                }
            });
        ctx.get().setPacketHandled(true);
    }

    /**
     * Handle the packet on the client side.
     * Opens the merchant trading screen.
     */
    @OnlyIn(Dist.CLIENT)
    private void handleClient() {
        net.minecraft.client.Minecraft mc =
            net.minecraft.client.Minecraft.getInstance();
        mc.setScreen(
            new com.tiedup.remake.client.gui.screens.MerchantTradingScreen(
                merchantUUID,
                trades
            )
        );

        TiedUpMod.LOGGER.debug(
            "[PacketOpenMerchantScreen] Opening merchant screen with {} trades",
            trades.size()
        );
    }
}
