#include <ItemRegistry/ItemRegistry.hpp>
#include <Widget/Builder/Builder.hpp>
#include <Widget/Label/Label.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Layout/CompoundWidget/CompoundWidget.hpp>
#include <Widget/Layout/CompoundWidget/ItemPicker/ItemPicker.hpp>
#include <Widget/Layout/Margin/Margin.hpp>
#include <Widget/Layout/Row/Row.hpp>
#include <Widget/Layout/ScrollPanel/ScrollPanel.hpp>
#include <Widget/Panel/Panel.hpp>
#include <Widget/StaticItemSlot/ItemSlotButton/ItemSlotButton.hpp>
#include <Widget/TextField/TextField.hpp>

ItemPicker::ItemPicker(SelectionCallback onSelected) :
    CompoundWidget(
        new Margin<compSpacing>(
            new Column(
                (new TextField(query))->withPlaceholder("Search items..."),
                new Panel(glm::ivec2(0, compSpacing)),
                new Builder<std::string>(
                    query,
                    [this, onSelected](std::string query) -> Widget*
                    {
                        filter.setQuery(query);

                        std::vector<Widget*> rows;
                        std::vector<Widget*> nextRow;

                        for (ItemStack &stack : allStacks)
                        {
                            if (!filter.matches(stack))
                            {
                                continue;
                            }

                            if (nextRow.size() == numCols)
                            {
                                rows.push_back(new Row(nextRow));
                                nextRow.clear();
                            }

                            nextRow.push_back(
                                new ItemSlotButton(
                                    stack,
                                    [stack, onSelected]()
                                    {
                                        onSelected(stack);
                                    }
                                )
                            );
                        }

                        if (nextRow.size() != 0)
                        {
                            rows.push_back(new Row(nextRow));
                        }

                        return new ScrollPanel(scrollPanelHeight, new Column(rows));
                    }
                )
            )
        )
    )
{
    itemRegistry.getAllStacks(allStacks);

    std::sort(allStacks.begin(), allStacks.end(), [](ItemStack &a, ItemStack &b)
    {
        std::string nameA = a.getDisplayName();
        std::string nameB = b.getDisplayName();

        return nameA < nameB;
    });
}