package net.halbear.skyboxmod.rendering.screen;

import net.halbear.skyboxmod.SkyboxMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.packs.TransferableSelectionList;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Util;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.neoforged.neoforge.client.event.ContainerScreenEvent;
import net.neoforged.neoforge.client.event.ScreenEvent;
import net.neoforged.neoforge.common.NeoForge;
import org.jspecify.annotations.NonNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

public class SelectionScreen extends Screen {

    private final Screen lastScreen;
    private final File targetDirectory;

    private final List<String> availableItems = new ArrayList<>(List.of("Test1", "Test2", "Test3", "Test4"));
    private final List<String> selectedItems = new ArrayList<>(List.of("Test5"));

    private final ConcurrentLinkedQueue<Button> transferButtons = new ConcurrentLinkedQueue<Button>();

    private SelectionPanelList leftList;
    private SelectionPanelList rightList;


    public SelectionScreen(Screen lastScreen, File targetDirectory) {
        super(Component.literal("Select Custom Options"));
        this.lastScreen = lastScreen;
        this.targetDirectory = targetDirectory;
    }

    @Override
    protected void init() {
        super.init();
        int listWidth = 170;
        int listHeight = this.height - 80;

        this.leftList = new SelectionPanelList(this.minecraft, listWidth, listHeight,40,24 );
        this.leftList.setX(this.width / 2 - 180);


        this.rightList = new SelectionPanelList(this.minecraft, listWidth, listHeight,40,24);
        this.rightList.setX(this.width / 2 + 10);

        refreshListData();

        this.addRenderableWidget(this.leftList);
        this.addRenderableWidget(this.rightList);

        this.addRenderableWidget(Button.builder(
                Component.literal("Done"),
                button -> this.onClose()
        ).bounds(this.width / 2 - 75, this.height - 32, 150, 20).build());
    }

    private void refreshListData() {

        Button TransferBtn;
        while ((TransferBtn = transferButtons.poll()) != null) {
            renderables.remove(TransferBtn);
        }

        this.leftList.clearEntries();
        this.rightList.clearEntries();

        for (String item : availableItems) {
            this.leftList.AddEntry(new TextRowEntry(item, true,this));
        }
        for (String item : selectedItems) {
            this.rightList.AddEntry(new TextRowEntry(item, false,this));
        }
    }

    @Override
    public void extractBackground(GuiGraphicsExtractor guiGraphics, int mouseX, int mouseY, float partialTick) {
        super.extractBackground(guiGraphics, mouseX, mouseY, partialTick);
        guiGraphics.pose().pushMatrix();
        guiGraphics.text(this.font, this.title, this.width / 2 - this.font.width(this.title)/2, 8, 0xFFFFFFFF,true);
        guiGraphics.text(this.font, "Drag and drop sprites inside...", this.width / 2 - this.font.width("Drag and drop sprites inside...")/2, 20, 0xFFFFFFFF,true);
        guiGraphics.pose().popMatrix();

        // NeoForge.EVENT_BUS.post(new ScreenEvent.Render.Post(this,guiGraphicsExtractor, mouseX, mouseY,partialTick));

        //SkyboxMod.LOGGER.debug("\n this font: " + this.font + "\n this width:" + this.width + "\n this Title: " + this.title + "\n this title width: " + this.font.width(this.title));
    }

    @Override
    public void extractRenderState(GuiGraphicsExtractor guiGraphicsExtractor, int mouseX, int mouseY, float partialTick){
        super.extractRenderState(guiGraphicsExtractor,mouseX,mouseY,partialTick);

    }

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


    private class SelectionPanelList extends ObjectSelectionList<TextRowEntry> {

        public SelectionPanelList(Minecraft minecraft, int width, int height, int y, int itemHeight) {
            super(minecraft, width, height, y, itemHeight);
        }
        public void AddEntry(TextRowEntry entry){
            this.addEntry(entry);
        }
        @Override
        public int getRowWidth() {
            return getWidth() - this.scrollbarWidth();
        }

        public void ClearChildren(){
            this.clearEntries();
        }
    }

    private class TextRowEntry extends ObjectSelectionList.Entry<TextRowEntry> {
        private final String textValue;
        private final Button transferButton;
        private final SelectionScreen Parent;

        public TextRowEntry(String value, boolean isAvailableSide, SelectionScreen Parent) {
            this.Parent = Parent;
            this.textValue = value;

            String buttonSymbol = isAvailableSide ? "➡" : "⬅";
            this.transferButton = Button.builder(Component.literal(buttonSymbol), button -> {
                if (isAvailableSide) {
                    availableItems.remove(textValue);
                    selectedItems.add(textValue);
                } else {
                    selectedItems.remove(textValue);
                    availableItems.add(textValue);
                }
                refreshListData();
            }).bounds(0, 0, 20, 20).build();
            transferButtons.add(this.transferButton);
            Parent.addRenderableWidget(this.transferButton);
        }

        @Override
        public void extractContent(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, boolean isHovered, float partialTick) {
            int left = this.getX();
            int top = this.getY();
            int rowWidth = this.getWidth();
            int rowHeight = this.getHeight();
            graphics.pose().pushMatrix();
            this.transferButton.setX(left + rowWidth - (transferButton.getWidth() + 2));
            this.transferButton.setY(top + rowHeight/2 - transferButton.getWidth()/2);
            graphics.pose().translate((float)left, (float)top);
           // SkyboxMod.LOGGER.debug("\n this font: " + Parent.getFont() + "\n this rowWidth:" + rowWidth + "\n this Text: " + this.textValue + "\n this Position: " + left +"_"+top);
            graphics.blit( Identifier.fromNamespaceAndPath(SkyboxMod.MODID, "textures/no_texture.png"),0, 0, 20,  20,0,1,0,1);
            graphics.text(Parent.getFont(), this.textValue, 24, 6, 0xFFFFFFFF, true);
            this.transferButton.extractRenderState(graphics, mouseX, mouseY, partialTick);
            graphics.pose().popMatrix();
        }

        @Override
        public boolean mouseClicked(MouseButtonEvent event, boolean doubleclicked) {
            if (this.transferButton.mouseClicked(event, doubleclicked)) {
                return true;
            }
            return super.mouseClicked(event, doubleclicked);
        }

        @Override
        public Component getNarration() {
            return Component.literal(this.textValue);
        }
    }

}
