package net.minecraft.client.gui.screens.reporting;

import com.mojang.authlib.minecraft.report.AbuseReportLimits;
import java.util.function.Consumer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ActiveTextCollector;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.TextAlignment;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.MultiLineLabel;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.navigation.ScreenDirection;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.DividerEntry;
import net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Heading;
import net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.MessageEntry;
import net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.MessageHeadingEntry;
import net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.PaddingEntry;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.multiplayer.chat.ChatTrustLevel;
import net.minecraft.client.multiplayer.chat.GuiMessageTag;
import net.minecraft.client.multiplayer.chat.LoggedChatMessage;
import net.minecraft.client.multiplayer.chat.report.ChatReport;
import net.minecraft.client.multiplayer.chat.report.ReportingContext;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Mth;
import org.jspecify.annotations.Nullable;

@Environment(EnvType.CLIENT)
public class ChatSelectionScreen extends Screen {
	private static final Identifier CHECKMARK_SPRITE = Identifier.withDefaultNamespace("icon/checkmark");
	private static final Component TITLE = Component.translatable("gui.chatSelection.title");
	private static final Component CONTEXT_INFO = Component.translatable("gui.chatSelection.context");
	private final @Nullable Screen lastScreen;
	private final ReportingContext reportingContext;
	private Button confirmSelectedButton;
	private MultiLineLabel contextInfoLabel;
	private ChatSelectionScreen.@Nullable ChatSelectionList chatSelectionList;
	private final ChatReport.Builder report;
	private final Consumer<ChatReport.Builder> onSelected;
	private ChatSelectionLogFiller chatLogFiller;

	public ChatSelectionScreen(
		final @Nullable Screen lastScreen, final ReportingContext reportingContext, final ChatReport.Builder report, final Consumer<ChatReport.Builder> onSelected
	) {
		super(TITLE);
		this.lastScreen = lastScreen;
		this.reportingContext = reportingContext;
		this.report = report.copy();
		this.onSelected = onSelected;
	}

	@Override
	protected void init() {
		this.chatLogFiller = new ChatSelectionLogFiller(this.reportingContext, this::canReport);
		this.contextInfoLabel = MultiLineLabel.create(this.font, CONTEXT_INFO, this.width - 16);
		this.chatSelectionList = this.addRenderableWidget(new ChatSelectionScreen.ChatSelectionList(this.minecraft, (this.contextInfoLabel.getLineCount() + 1) * 9));
		this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, b -> this.onClose()).bounds(this.width / 2 - 155, this.height - 32, 150, 20).build());
		this.confirmSelectedButton = this.addRenderableWidget(Button.builder(CommonComponents.GUI_DONE, b -> {
			this.onSelected.accept(this.report);
			this.onClose();
		}).bounds(this.width / 2 - 155 + 160, this.height - 32, 150, 20).build());
		this.updateConfirmSelectedButton();
		this.extendLog();
		this.chatSelectionList.setScrollAmount(this.chatSelectionList.maxScrollAmount());
	}

	private boolean canReport(final LoggedChatMessage message) {
		return message.canReport(this.report.reportedProfileId());
	}

	private void extendLog() {
		int pageSize = this.chatSelectionList.getMaxVisibleEntries();
		this.chatLogFiller.fillNextPage(pageSize, this.chatSelectionList);
	}

	private void onReachedScrollTop() {
		this.extendLog();
	}

	private void updateConfirmSelectedButton() {
		this.confirmSelectedButton.active = !this.report.reportedMessages().isEmpty();
	}

	@Override
	public void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a) {
		super.extractRenderState(graphics, mouseX, mouseY, a);
		ActiveTextCollector textRenderer = graphics.textRenderer();
		graphics.centeredText(this.font, this.title, this.width / 2, 10, -1);
		AbuseReportLimits reportLimits = this.reportingContext.sender().reportLimits();
		int messageCount = this.report.reportedMessages().size();
		int maxMessageCount = reportLimits.maxReportedMessageCount();
		Component selectedText = Component.translatable("gui.chatSelection.selected", messageCount, maxMessageCount);
		graphics.centeredText(this.font, selectedText, this.width / 2, 26, -1);
		int topY = this.chatSelectionList.getFooterTop();
		this.contextInfoLabel.visitLines(TextAlignment.CENTER, this.width / 2, topY, 9, textRenderer);
	}

	@Override
	public void onClose() {
		this.minecraft.gui.setScreen(this.lastScreen);
	}

	@Override
	public Component getNarrationMessage() {
		return CommonComponents.joinForNarration(super.getNarrationMessage(), CONTEXT_INFO);
	}

	@Environment(EnvType.CLIENT)
	public class ChatSelectionList
		extends ObjectSelectionList<net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry>
		implements ChatSelectionLogFiller.Output {
		public static final int ITEM_HEIGHT = 16;
		private @Nullable Heading previousHeading;

		public ChatSelectionList(final Minecraft minecraft, final int upperMargin) {
			super(minecraft, ChatSelectionScreen.this.width, ChatSelectionScreen.this.height - upperMargin - 80, 40, 16);
		}

		@Override
		public void setScrollAmount(final double scrollAmount) {
			double prevScrollAmount = this.scrollAmount();
			super.setScrollAmount(scrollAmount);
			if (this.maxScrollAmount() > 1.0E-5F && scrollAmount <= 1.0E-5F && !Mth.equal(scrollAmount, prevScrollAmount)) {
				ChatSelectionScreen.this.onReachedScrollTop();
			}
		}

		@Override
		public void acceptMessage(final int id, final LoggedChatMessage.Player message) {
			boolean canReport = message.canReport(ChatSelectionScreen.this.report.reportedProfileId());
			ChatTrustLevel trustLevel = message.trustLevel();
			GuiMessageTag tag = trustLevel.createTag(message.message());
			net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry entry = new MessageEntry(
				this, id, message.toContentComponent(), message.toNarrationComponent(), tag, canReport, true
			);
			this.addEntryToTop(entry);
			this.updateHeading(message, canReport);
		}

		private void updateHeading(final LoggedChatMessage.Player message, final boolean canReport) {
			net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry entry = new MessageHeadingEntry(
				this, message.profile(), message.toHeadingComponent(), canReport
			);
			this.addEntryToTop(entry);
			Heading heading = new Heading(message.profileId(), entry);
			if (this.previousHeading != null && this.previousHeading.canCombine(heading)) {
				this.removeEntryFromTop(this.previousHeading.entry());
			}

			this.previousHeading = heading;
		}

		@Override
		public void acceptDivider(final Component text) {
			this.addEntryToTop(new PaddingEntry());
			this.addEntryToTop(new DividerEntry(this, text));
			this.addEntryToTop(new PaddingEntry());
			this.previousHeading = null;
		}

		@Override
		public int getRowWidth() {
			return Math.min(350, this.width - 50);
		}

		public int getMaxVisibleEntries() {
			return Mth.positiveCeilDiv(this.height, 16);
		}

		protected void extractItem(
			final GuiGraphicsExtractor graphics,
			final int mouseX,
			final int mouseY,
			final float a,
			final net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry entry
		) {
			if (this.shouldHighlightEntry(entry)) {
				boolean selected = this.getSelected() == entry;
				int outlineColor = this.isFocused() && selected ? -1 : -8355712;
				this.extractSelection(graphics, entry, outlineColor);
			}

			entry.extractContent(graphics, mouseX, mouseY, this.getHovered() == entry, a);
		}

		private boolean shouldHighlightEntry(final net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry entry) {
			if (entry.canSelect()) {
				boolean entrySelected = this.getSelected() == entry;
				boolean nothingSelected = this.getSelected() == null;
				boolean entryHovered = this.getHovered() == entry;
				return entrySelected || nothingSelected && entryHovered && entry.canReport();
			} else {
				return false;
			}
		}

		protected @Nullable Entry nextEntry(final ScreenDirection dir) {
			return this.nextEntry(dir, net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry::canSelect);
		}

		public void setSelected(final @Nullable Entry selected) {
			super.setSelected(selected);
			net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry entry = this.nextEntry(ScreenDirection.UP);
			if (entry == null) {
				ChatSelectionScreen.this.onReachedScrollTop();
			}
		}

		@Override
		public boolean keyPressed(final KeyEvent event) {
			net.minecraft.client.gui.screens.reporting.ChatSelectionScreen.ChatSelectionList.Entry selected = this.getSelected();
			return selected != null && selected.keyPressed(event) ? true : super.keyPressed(event);
		}

		public int getFooterTop() {
			return this.getBottom() + 9;
		}
	}
}
