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

import com.tiedup.remake.client.gui.util.GuiColors;
import com.tiedup.remake.client.gui.util.GuiLayoutConstants;
import com.tiedup.remake.core.TiedUpMod;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.trader.PacketBuyCaptive;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Trading screen for the SlaveTrader.
 *
 * Displays list of captives available for purchase and allows buying.
 *
 * Layout:
 * ┌─────────────────────────────────────────┐
 * │          SLAVE TRADER                   │
 * │                                         │
 * │  [Name] - [Price]              [BUY]    │
 * │  [Name] - [Price]              [BUY]    │
 * │  [Name] - [Price]              [BUY]    │
 * │                                         │
 * │              [Close]                    │
 * └─────────────────────────────────────────┘
 */
@OnlyIn(Dist.CLIENT)
public class SlaveTraderScreen extends BaseScreen {

    private final int traderEntityId;
    private final String traderName;
    private final List<CaptiveOffer> offers;

    private static final int ROW_HEIGHT = 28;
    private static final int BUY_BUTTON_WIDTH = 50;
    private static final int BUY_BUTTON_HEIGHT = 18;

    /**
     * Data class representing a captive available for purchase.
     */
    public static class CaptiveOffer {

        public final UUID captiveId;
        public final String captiveName;
        public final String priceDescription;
        public final int priceAmount;
        public final String priceItemId;

        public CaptiveOffer(
            UUID captiveId,
            String captiveName,
            String priceDescription,
            int priceAmount,
            String priceItemId
        ) {
            this.captiveId = captiveId;
            this.captiveName = captiveName;
            this.priceDescription = priceDescription;
            this.priceAmount = priceAmount;
            this.priceItemId = priceItemId;
        }
    }

    public SlaveTraderScreen(
        int traderEntityId,
        String traderName,
        List<CaptiveOffer> offers
    ) {
        super(Component.translatable("gui.tiedup.slave_trader"));
        this.traderEntityId = traderEntityId;
        this.traderName = traderName;
        this.offers = offers != null ? offers : new ArrayList<>();
    }

    @Override
    protected int getPreferredWidth() {
        return GuiLayoutConstants.getResponsiveWidth(
            this.width,
            0.5f,
            320,
            400
        );
    }

    @Override
    protected int getPreferredHeight() {
        int offerHeight = Math.max(1, offers.size()) * ROW_HEIGHT;
        int baseHeight =
            GuiLayoutConstants.TITLE_HEIGHT +
            50 +
            GuiLayoutConstants.BUTTON_HEIGHT +
            30;
        return GuiLayoutConstants.getResponsiveHeight(
            this.height,
            0.8f,
            180,
            Math.min(400, baseHeight + offerHeight)
        );
    }

    @Override
    protected void init() {
        super.init();

        int contentTop = this.topPos + GuiLayoutConstants.TITLE_HEIGHT + 15;
        int centerX = this.leftPos + this.imageWidth / 2;

        // Add buy button for each offer
        int y = contentTop;
        for (int i = 0; i < offers.size(); i++) {
            CaptiveOffer offer = offers.get(i);
            int buttonX =
                this.leftPos + this.imageWidth - BUY_BUTTON_WIDTH - 15;
            int buttonY = y + (ROW_HEIGHT - BUY_BUTTON_HEIGHT) / 2;

            final int index = i;
            Button buyBtn = Button.builder(
                Component.translatable("gui.tiedup.buy"),
                b -> onBuy(index)
            )
                .bounds(buttonX, buttonY, BUY_BUTTON_WIDTH, BUY_BUTTON_HEIGHT)
                .build();
            this.addRenderableWidget(buyBtn);

            y += ROW_HEIGHT;
        }

        // Close button at bottom
        int closeY =
            this.topPos +
            this.imageHeight -
            GuiLayoutConstants.BUTTON_HEIGHT -
            10;
        Button closeBtn = Button.builder(
            Component.translatable("gui.tiedup.close"),
            b -> onClose()
        )
            .bounds(centerX - 40, closeY, 80, GuiLayoutConstants.BUTTON_HEIGHT)
            .build();
        this.addRenderableWidget(closeBtn);
    }

    private void onBuy(int offerIndex) {
        if (offerIndex < 0 || offerIndex >= offers.size()) {
            return;
        }

        CaptiveOffer offer = offers.get(offerIndex);

        TiedUpMod.LOGGER.info(
            "[SlaveTraderScreen] Attempting to buy captive {} from trader {}",
            offer.captiveId.toString().substring(0, 8),
            traderEntityId
        );

        // Send buy request to server
        ModNetwork.sendToServer(
            new PacketBuyCaptive(traderEntityId, offer.captiveId)
        );

        // Close screen after purchase attempt
        onClose();
    }

    @Override
    public void render(
        GuiGraphics graphics,
        int mouseX,
        int mouseY,
        float partialTick
    ) {
        super.render(graphics, mouseX, mouseY, partialTick);

        int contentTop = this.topPos + GuiLayoutConstants.TITLE_HEIGHT + 15;
        int leftX = this.leftPos + 15;

        // Render trader name
        graphics.drawString(
            this.font,
            traderName,
            leftX,
            this.topPos + GuiLayoutConstants.TITLE_HEIGHT + 2,
            GuiColors.TEXT_WHITE
        );

        // Render offers
        if (offers.isEmpty()) {
            graphics.drawString(
                this.font,
                Component.translatable(
                    "gui.tiedup.no_captives_available"
                ).withStyle(ChatFormatting.GRAY),
                leftX,
                contentTop + 10,
                GuiColors.TEXT_GRAY
            );
        } else {
            int y = contentTop;
            for (CaptiveOffer offer : offers) {
                renderOfferRow(graphics, offer, leftX, y);
                y += ROW_HEIGHT;
            }
        }
    }

    private void renderOfferRow(
        GuiGraphics graphics,
        CaptiveOffer offer,
        int x,
        int y
    ) {
        // Captive name
        graphics.drawString(
            this.font,
            offer.captiveName,
            x,
            y + 2,
            GuiColors.TEXT_WHITE
        );

        // Price
        graphics.drawString(
            this.font,
            offer.priceDescription,
            x,
            y + 14,
            GuiColors.TEXT_GRAY
        );
    }

    @Override
    public boolean isPauseScreen() {
        return false;
    }
}
