import { __ } from "@wordpress/i18n";
import { getSitePluginsQueryOptions } from "@/shared/site-plugins/query-options";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useMemo } from "@wordpress/element";
import { getPluginDataQueryOptions } from "@/shared/ploogins-search/query-options";
import { Icon } from "@wordpress/components";
import { download } from "@wordpress/icons";
import PluginsView from "../PluginsView";
import usePluginsViewStore from "@/stores/pluginsViewStore";

const Installed = () => {

    const { data: sitePlugins } = useQuery(getSitePluginsQueryOptions())

    const pluginSlugs = sitePlugins?.map((plugin) => plugin.plugin.split('/')[0]).filter((slug) => slug !== ''); 

    const { data: pluginQueries, isLoading } = useQuery(getPluginDataQueryOptions(pluginSlugs ?? []));

    const data = useMemo(() => {
        if (!sitePlugins) return [];
        
        return sitePlugins.map((plugin, index) => {
            return pluginQueries?.[index] as WordPressPlugin | undefined;
        }).filter((plugin): plugin is WordPressPlugin => plugin !== undefined);
    }, [sitePlugins, pluginQueries]);

    const { setData, setIsPending } = usePluginsViewStore()

    useEffect(() => {
        setData(data)
    }, [data])

    useEffect(() => {
        setIsPending(isLoading)
    }, [isLoading])

    return (
        <div className="h-full flex flex-col">

            <header style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0' }} className="sticky top-0 bg-white flex justify-between items-center">
                <div className="flex items-center gap-2">
                    <Icon icon={download} className="w-4 h-4 md:w-6 md:h-6" />
                    <h2 className="!text-base md:!text-lg !font-medium !py-0 !my-0">{__('Installed Plugins', 'ploogins-ai-assistant')}</h2>
                </div>

                <div className="flex items-center gap-2">
                    <span className="!text-sm !font-normal !my-0 !py-0">{data?.length} {__('plugins', 'ploogins-ai-assistant')}</span>
                </div>
            </header>

            <PluginsView />
        </div>
    );

}

export default Installed