import React, {ReactNode} from "react";
import {mapValues, values} from "lodash";
import {componentCategories} from "./tree/components";
import {ProBadge} from "./ProBadge";

export type SelectableListProps<Item> = {
    categorizedItems: Record<string, Item[]>
    categoryData: Record<string, {
        label: string,
        // here possible in the future to add 'desc', 'icon', 'style', etc.
    }>,
    itemRenderer: {
        customRender: (item: Item, selectItem: () => void) => React.ReactNode;
        example?: (item: Item) => ReactNode,
        icon?: (item: Item, defaults: {className: string}) => any,
        content: (item: Item) => ReactNode,
        renderProBadge?: (item: Item) => boolean
    },
    onSelect: (item: Item) => void,
}

export function SelectableList<Item>({categorizedItems, categoryData, itemRenderer, onSelect}: SelectableListProps<Item>) {
    return <div className="relative flex flex-col space-y-6 mb-4">
        {values(mapValues(categorizedItems, (items, category) => {
            if (!items?.length) {
                return null;
            }
            return <div className="space-y-2">
                <div className="text-smaller-1 text-gray-400">{componentCategories[category]?.label ?? componentCategories[category]}</div>
                <div className="space-y-3">
                    {items.map((item) => {
                        const example = itemRenderer.example?.(item)
                        const selectItem = () => onSelect(item)

                        if (itemRenderer?.customRender) {
                            return itemRenderer.customRender(item, selectItem)
                        }

                        return <div className="space-y-1">
                            <button
                                className="flex items-center space-x-3 py-[8px] px-7 text-gray-800 rounded-2 border-px border-gray-200 w-full hover:bg-purple-tint-10 hover:border-purple-tint-50 hover:bg-opacity-50 group"
                                onClick={selectItem}>
                                {itemRenderer.icon?.(item, {className: "w-5 h-5 text-gray-350 group-hover:text-purple-tint-90"})}
                                <div className="flex flex-col items-start space-y-0">
                                    <div className="space-x-1 flex items-center gap-2">
                                        <div className="flex items-center gap-1">
                                            <p className={"text-1x font-medium group-hover:text-purple-tint-90"}>{itemRenderer.content(item)}</p>
                                        </div>
                                        {itemRenderer.renderProBadge?.(item) && <ProBadge /> }
                                    </div>
                                </div>
                            </button>
                            {example}
                        </div>
                    })}
                </div>
            </div>
        }))}
    </div>
}
