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

import com.tiedup.remake.bounty.Bounty;
import com.tiedup.remake.client.gui.util.GuiColors;
import com.tiedup.remake.client.gui.util.GuiLayoutConstants;
import com.tiedup.remake.client.gui.widgets.BountyEntryWidget;
import com.tiedup.remake.network.ModNetwork;
import com.tiedup.remake.network.bounty.PacketDeleteBounty;
import java.util.List;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.ContainerObjectSelectionList;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Screen displaying all active bounties.
 * Refactored to use standard ContainerObjectSelectionList.
 */
@OnlyIn(Dist.CLIENT)
public class BountyListScreen extends BaseScreen {

    private final List<Bounty> bounties;
    private final boolean isAdmin;

    private BountyList bountyList;
    private Button closeButton;
    private Button deleteButton;

    public BountyListScreen(List<Bounty> bounties, boolean isAdmin) {
        super(Component.translatable("gui.tiedup.bounties.title"));
        this.bounties = bounties;
        this.isAdmin = isAdmin;
    }

    @Override
    protected int getPreferredWidth() {
        return GuiLayoutConstants.getResponsiveWidth(
            this.width,
            0.7f,
            350,
            500
        );
    }

    @Override
    protected int getPreferredHeight() {
        return GuiLayoutConstants.getResponsiveHeight(
            this.height,
            0.8f,
            250,
            400
        );
    }

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

        int listTop = this.topPos + GuiLayoutConstants.TITLE_HEIGHT + 20;
        int listBottom =
            this.topPos +
            this.imageHeight -
            GuiLayoutConstants.BUTTON_HEIGHT * 2 -
            20;
        int listHeight = listBottom - listTop;

        // Initialize List
        bountyList = new BountyList(
            minecraft,
            this.imageWidth - 20,
            listHeight,
            listTop,
            listBottom
        );
        bountyList.setLeftPos(this.leftPos + 10);

        // Populate List
        for (Bounty bounty : bounties) {
            bountyList.addEntryPublic(
                new BountyEntryWidget(bounty, this::onEntrySelected)
            );
        }
        this.addRenderableWidget(bountyList);

        // Buttons
        int btnWidth = GuiLayoutConstants.BUTTON_WIDTH_XL;
        int btnX = this.leftPos + (this.imageWidth - btnWidth) / 2;
        int btnY = listBottom + 10;

        deleteButton = Button.builder(
            Component.translatable("gui.tiedup.bounties.delete"),
            b -> onDeleteClicked()
        )
            .bounds(btnX, btnY, btnWidth, GuiLayoutConstants.BUTTON_HEIGHT)
            .build();
        deleteButton.active = false;
        this.addRenderableWidget(deleteButton);

        closeButton = Button.builder(
            Component.translatable("gui.tiedup.close"),
            b -> onClose()
        )
            .bounds(
                btnX,
                btnY + GuiLayoutConstants.BUTTON_HEIGHT + 4,
                btnWidth,
                GuiLayoutConstants.BUTTON_HEIGHT
            )
            .build();
        this.addRenderableWidget(closeButton);
    }

    private void onEntrySelected(BountyEntryWidget entry) {
        bountyList.setSelected(entry);
        updateDeleteButton();
    }

    private void updateDeleteButton() {
        BountyEntryWidget selected = bountyList.getSelected();
        if (selected == null) {
            deleteButton.active = false;
            return;
        }

        Bounty bounty = selected.getBounty();
        if (minecraft.player == null) {
            deleteButton.active = false;
            return;
        }
        UUID playerId = minecraft.player.getUUID();

        // Can delete if admin or bounty client
        deleteButton.active = isAdmin || bounty.isClient(playerId);

        // Update visual selection state in all widgets
        for (BountyEntryWidget w : bountyList.children()) {
            w.setSelected(w == selected);
        }
    }

    private void onDeleteClicked() {
        BountyEntryWidget selected = bountyList.getSelected();
        if (selected == null) return;

        Bounty bounty = selected.getBounty();
        ModNetwork.sendToServer(new PacketDeleteBounty(bounty.getId()));

        // Remove from list
        bounties.remove(bounty);
        bountyList.removeEntryPublic(selected);

        // Reset selection
        bountyList.setSelected(null);
        updateDeleteButton();
    }

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

        // Bounty count
        String countText =
            bounties.size() + " bounti" + (bounties.size() != 1 ? "es" : "y");
        graphics.drawString(
            this.font,
            countText,
            this.leftPos + GuiLayoutConstants.MARGIN_M,
            this.topPos + GuiLayoutConstants.TITLE_HEIGHT + 2,
            GuiColors.TEXT_GRAY
        );

        // Empty state
        if (bounties.isEmpty()) {
            graphics.drawCenteredString(
                this.font,
                Component.translatable("gui.tiedup.bounties.noEntries"),
                this.leftPos + this.imageWidth / 2,
                this.topPos + this.imageHeight / 2,
                GuiColors.TEXT_DISABLED
            );
        }

        // Render tooltip for hovered entry
        BountyEntryWidget hovered = bountyList.getEntryAtPositionPublic(
            mouseX,
            mouseY
        );
        if (hovered != null) {
            graphics.renderTooltip(
                this.font,
                hovered.getBounty().getReward(),
                mouseX,
                mouseY
            );
        }
    }

    // ==================== INNER CLASS: LIST ====================

    class BountyList extends ContainerObjectSelectionList<BountyEntryWidget> {

        public BountyList(
            Minecraft mc,
            int width,
            int height,
            int top,
            int bottom
        ) {
            super(mc, width, height, top, bottom, 55); // 55 = item height
            this.centerListVertically = false;
            this.setRenderBackground(false);
            this.setRenderTopAndBottom(false);
        }

        public void addEntryPublic(BountyEntryWidget entry) {
            this.addEntry(entry);
        }

        public void removeEntryPublic(BountyEntryWidget entry) {
            this.removeEntry(entry);
        }

        public BountyEntryWidget getEntryAtPositionPublic(double x, double y) {
            return super.getEntryAtPosition(x, y);
        }

        @Override
        public int getRowWidth() {
            return this.width - 20;
        }

        @Override
        protected int getScrollbarPosition() {
            return this.getLeft() + this.width - 6;
        }

        public void setLeftPos(int left) {
            this.x0 = left;
            this.x1 = left + this.width;
        }

        @Override
        public int getRowLeft() {
            return BountyListScreen.this.leftPos + 10;
        }
    }
}
