import { addActivityMutationOptions } from "@/shared/plugin-activity/mutation-options"
import { getSitePluginsQueryOptions } from "@/shared/site-plugins/query-options"
import { extractChildrenFromTag } from "@/shared/utils/html"
import usePluginSelectedStore from "@/stores/pluginSelectedStore"
import { useMutation, useQuery } from "@tanstack/react-query"
import { decodeEntities } from "@wordpress/html-entities"
import { useEffect, useMemo } from "@wordpress/element"
import usePluginsViewStore from "@/stores/pluginsViewStore"
import { getPluginStatus } from "@/shared/site-plugins/utils/index."
import { Icon, Spinner } from "@wordpress/components"
import { check, download } from "@wordpress/icons"
import { __ } from "@wordpress/i18n"

const PluginList = () => {

    const { data: plugins_data, isPending, setIsOpen } = usePluginsViewStore()

    const { data: sitePlugins } = useQuery(getSitePluginsQueryOptions())
    const { plugin: selectedPlugin, setPlugin } = usePluginSelectedStore()

    const addActivityMutation = useMutation(addActivityMutationOptions())

    useEffect(() => {
        if (selectedPlugin) {
            addActivityMutation.mutate({
                plugin_slug: selectedPlugin.slug,
                activity_type: 'view',
            })
        }
    }, [selectedPlugin])

    useEffect(() => {
        if (plugins_data.length > 0 && window.innerWidth > 768) {
            setPlugin(plugins_data[0])
        } else {
            setPlugin(null)
        }
    }, [plugins_data])

    const handleClick = (plugin: WordPressPlugin) => {
        setPlugin(plugin)
        setIsOpen(true)
    }

    const pluginList = useMemo(() => {
        return plugins_data.map((pluginData) => {
            const { isActive, isInstalled } = getPluginStatus(sitePlugins ?? [], pluginData.slug);

            return {
                ...pluginData,
                isActive,
                isInstalled,
            };
        });
    }, [plugins_data, sitePlugins])

    return (
        <div className="h-full flex flex-col overflow-y-auto divide-y divide-neutral-200" style={{ borderRight: '1px solid #f0f0f0' }}>

            {isPending && (
                <div className="flex items-center justify-center h-full">
                    <Spinner />
                </div>
            )}

            {!isPending && pluginList.map((plugin) => (
                <button key={plugin.slug} className={`relative flex items-center gap-4 p-4 pl-6 cursor-pointer ${plugin.isActive ? 'bg-blue-50 hover:bg-blue-100' : 'hover:bg-neutral-100'} ${selectedPlugin?.slug === plugin.slug ? 'ring-2 ring-blue-500 ring-inset' : ''}`} onClick={() => handleClick(plugin)}>
                    <img src={plugin.icons ? Object.values(plugin.icons).pop() : undefined} alt={plugin.name} className="w-8 h-8 md:w-10 md:h-10" />
                    <div className="text-left">
                        <p className="!text-sm !m-0">{decodeEntities(plugin.name)}</p>
                        <p className="!text-sm !m-0 text-neutral-500">{decodeEntities(extractChildrenFromTag(plugin.author, 'a'))}</p>
                    </div>

                    {plugin.isActive && (
                        <div className="absolute left-0 top-0 bottom-0 w-4 flex items-center justify-center" title={__('Active', 'ploogins-ai-assistant')}>
                            <Icon className="fill-blue-400 w-6 h-6" icon={check} />
                        </div>
                    )}

                    {plugin.isInstalled && (
                        <div className="absolute right-5 top-2" title={__('Installed', 'ploogins-ai-assistant')}>
                            <Icon icon={download} className="w-4 h-4 fill-neutral-500" />
                        </div>
                    )}

                </button>
            ))}
        </div>
    )
}

export default PluginList