package jesse.keeblarcraft.ChatStuff;

import java.util.ArrayList;
import java.util.List;

import jesse.keeblarcraft.ChatStuff.ChatFormatting.COLOR_CODE;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;

// Create a "chat menu" which is just a menu in chat with pages that a user can click to display
// the next page.
public class ChatMenu {
    private ArrayList<Text> msgList = new ArrayList<>();
    private Text header;
    private Text headerFooterSpacing = Text.of(" ");
    private Text leftArrow;
    private Text rightArrow;
    private int pageLimit = 25; // Messages per page in this menu (//TODO: This is being increased to show all info at once. Need to add callback to flip a page somehow)
    private int pageCount = 1; // Calculated at runtime
    private ChatMsg formatter = new ChatMsg();
    private int currentPage = 0;
    ServerPlayerEntity lastTarget;

    private enum TURN_DIRECTION {
        BACK,
        FORWARD
    }

    public ChatMenu() {
        // Initialize default header and arrows
        header = Text.of("[----- HELP MENU -----]");
        header = formatter.ColorMsg(header, COLOR_CODE.GOLD);

        leftArrow = Text.of("<<");
        leftArrow = formatter.ColorMsg(leftArrow, COLOR_CODE.GOLD);

        rightArrow = Text.of(">>");
        rightArrow = formatter.ColorMsg(rightArrow, COLOR_CODE.GOLD);
    }

    public void SetHeader(Text header) {
        this.header = header;
    }

    public void SetHeader(ChatMsg msg) {
        this.header = msg.mutableText;
    }

    public void SetLeftArrow(Text leftArrow) {
        this.leftArrow = leftArrow;
    }

    public void SetRightArrow(Text rightArrow) {
        this.rightArrow = rightArrow;
    }

    private Text MakeFooter() {
        // leftArrow = (Text) formatter.MakeClickCallback((MutableText) leftArrow, new ChatMsgClickEvent(() -> TurnPage(TURN_DIRECTION.BACK)));
        // leftArrow = Text.literal("TEST").styled(style -> style.withClickEvent(new ChatMsgClickEvent(() -> {
        //     System.out.println("Click event called from server");
        // })));

        MutableText footer = (MutableText) leftArrow;

        // This spacing is arbitrary and may be changed in future. It just looks OK for now
        footer.append(Text.of("          "));

        // rightArrow = formatter.MakeClickCallback((MutableText) rightArrow, new ChatMsgClickEvent(() -> TurnPage(TURN_DIRECTION.FORWARD)));
        footer.append(rightArrow);

        return (Text) footer;
    }

    private void TurnPage(TURN_DIRECTION turn) {
        System.out.println("TurnPage called");
        // The page we need to turn to will be calculated as so:
        // msgList[index] where index = (0 + pageLimit) * currentPage(+- 1)
        pageCount = (int) Math.ceil(msgList.size() / (double) pageLimit);

        // Guard clause: Cannot turn further than end of all pages or before page 1
        if ((turn == TURN_DIRECTION.BACK && currentPage == 1) || (turn == TURN_DIRECTION.FORWARD && currentPage == pageCount)) {
            return;
        }

        // Adjust new page number
        if (turn == TURN_DIRECTION.BACK) {
            --currentPage;
        } else {
            ++currentPage;
        }

        // Send updated message to player (msg takes care of printing page)
        if (lastTarget != null) {
            SendMsg(lastTarget);
        }
    }

    private Text MakeHeader() {
        MutableText head = (MutableText) Text.of("          ");
        head.append(header);
        head.append(Text.of("          "));

        header = (Text) head;

        return header;
    }

    public void AddMsg(Text newMsg) {
        msgList.add(newMsg);
    }

    public void AddMsg(String newMsg) {
        AddMsg(Text.of(newMsg));
    }

    public void AddMsg(ChatMsg newMsg) {
        AddMsg(newMsg.mutableText);
    }

    public void AddMsg(List<ChatMsg> newMsgList) {
        for (int i = 0; i < newMsgList.size(); i++) {
            AddMsg(newMsgList.get(i));
        }
    }

    public void AddNewLine() {
        AddMsg(Text.of(""));
    }

    public void ClearList() {
        msgList.clear();
        pageCount = 1;
    }

    public void SetPageLimit(int limit) {
        if (limit >= 1) {
            pageLimit = limit;
        }
    }

    // Prints the current page
    public void SendMsg(ServerPlayerEntity target) {
        // Calculate number of pages
        pageCount = (int) Math.ceil(msgList.size() / (double) pageLimit);
        int startIdx = currentPage * pageLimit;

        // Send the header
        target.sendMessage(MakeHeader());
        int maxCapoutDebug = 20;

        int stopIdx = startIdx + pageLimit;
        for (int pageItem = startIdx; pageItem < stopIdx && pageItem < msgList.size(); pageItem++) {
            target.sendMessage(msgList.get(pageItem));

            --maxCapoutDebug;

            if (maxCapoutDebug <= 0) {
                break;
            }
        }

        // Send the body
        // int msgIndex = 0;
        // for (int page = 0; page < pageCount && msgList.get(msgIndex) != null; page++) {
        //     for (int i = 0; i < pageLimit && msgList.get(msgIndex) != null; i++) {
        //         Text msg = msgList.get(msgIndex);
        //         if (msg == null) {
        //             target.sendMessage(msg);
        //         }
        //     }
        // }

        // Send the footer
        target.sendMessage(MakeFooter());

        // ChatMsg temp = new ChatMsg();
        // Text test = (Text) temp.MakeCopyableTxt("<<", "Click to copy", "Copied string");
        // Text test2 = (Text) temp.MakeCopyableTxt(">>", "Click to copy", "Copied");

        // MutableText temp3 = (MutableText) test;
        // temp3.append(test2);

        // target.sendMessage((Text) temp3);
    }
}
