import { useQuery } from "@tanstack/react-query";
import { __ } from "@wordpress/i18n";
import { getFeaturedPluginsQueryOptions } from "@/shared/ploogins-search/query-options";
import { decodeEntities } from "@wordpress/html-entities"
import { extractChildrenFromTag } from "@/shared/utils/html"
import usePluginSelectedStore from "@/stores/pluginSelectedStore";
import { useNavigate } from "@tanstack/react-router";

const FeaturedPlugins = () => {

    const { data: featuredPlugins, isPending } = useQuery(getFeaturedPluginsQueryOptions());

    const { setPlugin } = usePluginSelectedStore()

    const navigate = useNavigate()

    const handleClick = (plugin: WordPressPlugin) => {
        navigate({ to: '/featured' })
        setPlugin(plugin)
    }

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-between">
                <h2 className="!text-lg !font-medium !my-0 !py-0">{__('Featured Plugins', 'ploogins-ai-assistant')}</h2>
            </div>

            {isPending && <div className="text-sm text-gray-500">{__('Loading...', 'ploogins-ai-assistant')}</div>}

            {featuredPlugins && featuredPlugins.length > 0 && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {featuredPlugins.map((plugin) => (
                        <button onClick={() => handleClick(plugin)} role="button" key={plugin.slug} className="cursor-pointer border border-neutral-300 p-2 rounded-xl hover:border-neutral-700">
                            <div className="flex items-center gap-2">
                                <img className="w-10 h-10 object-cover rounded-lg" src={plugin.icons ? (() => { const keys = Object.keys(plugin.icons); const lastKey = keys.pop(); return lastKey ? (plugin.icons as any)[lastKey] ?? '' : ''; })() : ''} alt={plugin.name} />

                                <div className="flex-1 min-w-0 text-left">
                                    <h3 className="!text-sm !font-normal !my-0 !py-0 !line-clamp-1" title={decodeEntities(plugin.name)}>
                                        {decodeEntities(plugin.name)}
                                    </h3>
                                    <p className="!text-xs !text-neutral-500 !my-0 !py-0 !line-clamp-1">{extractChildrenFromTag(plugin.author, 'a')}</p>
                                </div>
                            </div>
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
};

export default FeaturedPlugins;