import usePluginSelectedStore from "@/stores/pluginSelectedStore"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { decodeEntities } from "@wordpress/html-entities"
import PluginSkeleton from "../PluginSkeleton"
import { Button } from "@wordpress/components"
import { __, sprintf } from "@wordpress/i18n"
import { autop } from '@wordpress/autop';
import { useSinglePlugin } from "@/hooks/useSinglePlugin"
import { getPluginInsightsQueryOptions } from "@/shared/suggerence-insights/query-options"

import { Icon } from "@wordpress/components"
import { starFilled, starEmpty, category, commentAuthorAvatar, check, store, external, arrowLeft } from "@wordpress/icons"
import useSearchStore from "@/stores/searchStore"
import { useNavigate } from "@tanstack/react-router"
import Activity from "./Activity"
import { addActivityMutationOptions } from "@/shared/plugin-activity/mutation-options"
import Notes from "./Notes"
import Related from "./Related"

import { installPluginMutationOptions, updatePluginStatusMutationOptions, deletePluginMutationOptions } from "@/shared/manage-plugins/mutation-options"
import usePluginsViewStore from "@/stores/pluginsViewStore"

const PluginDetails = () => {

    const { plugin, setPlugin } = usePluginSelectedStore()
    const navigate = useNavigate()
    const { isOpen, setIsOpen } = usePluginsViewStore()

    const { data: pluginInsights, isPending: isPluginInsightsPending } = useQuery(getPluginInsightsQueryOptions(plugin?.slug ?? ''))

    const queryClient = useQueryClient()
    const { setQuery } = useSearchStore()

    const { isActive, isInstalled, pluginDir } = useSinglePlugin({ slug: plugin?.slug ?? '' })

    const addActivityMutation = useMutation(addActivityMutationOptions())

    /**
     * Installation
     */

    const installPlugin = useMutation(installPluginMutationOptions())

    const handleInstallPlugin = () => {
        installPlugin.mutate(plugin?.slug ?? '')

        addActivityMutation.mutate({
            plugin_slug: plugin?.slug ?? '',
            activity_type: 'install',
        })
    }

    /**
     * Activation
     */

    const activatePlugin = useMutation(updatePluginStatusMutationOptions())

    const handleActivatePlugin = () => {
        activatePlugin.mutate({
            pluginSlug: plugin?.slug ?? '',
            status: 'active',
            plugin: pluginDir ?? '',
        })

        addActivityMutation.mutate({
            plugin_slug: plugin?.slug ?? '',
            activity_type: 'activate',
        })
    }

    /**
     * Deactivation
     */

    const deactivatePlugin = useMutation(updatePluginStatusMutationOptions())

    const handleDeactivatePlugin = () => {
        deactivatePlugin.mutate({
            pluginSlug: plugin?.slug ?? '',
            status: 'inactive',
            plugin: pluginDir ?? '',
        })

        addActivityMutation.mutate({
            plugin_slug: plugin?.slug ?? '',
            activity_type: 'deactivate',
        })
    }

    /**
     * Delete
     */

    const deletePlugin = useMutation(deletePluginMutationOptions())

    const handleDeletePlugin = () => {
        if (confirm(__('Are you sure you want to delete this plugin?', 'ploogins-ai-assistant'))) {
            deletePlugin.mutate({
                pluginSlug: plugin?.slug ?? '',
                plugin: pluginDir ?? '',
            })

            addActivityMutation.mutate({
                plugin_slug: plugin?.slug ?? '',
                activity_type: 'delete',
            })
        }
    }

    const isPremiumPlugin = plugin?.business_model === 'premium'

    const handleBackToPluginList = () => {
        setPlugin(null)
        setIsOpen(false)
    }

    return (
        <div className="w-full max-w-screen-lg mx-auto">

            <div className="sticky top-0 z-10 border-y border-neutral-100 md:!hidden flex justify-center mb-6 bg-neutral-100">
                <Button variant="tertiary" className={`flex items-center gap-2 p-2 cursor-pointer ${isOpen ? 'block' : 'hidden '}`} onClick={handleBackToPluginList}>
                    <Icon icon={arrowLeft} className="w-4 h-4" />
                    <span className="!text-sm !m-0">{__('Back to Plugin List', 'ploogins-ai-assistant')}</span>
                </Button>
            </div>

            {
                !plugin ? <PluginSkeleton /> : (
                    <div className="space-y-4 pb-12">


                        {
                            isPremiumPlugin && (
                                <div className="bg-blue-50 rounded p-2 justify-center flex items-center gap-1">
                                    <Icon className="fill-neutral-700" size={20} icon={store} />
                                    <span className="text-neutral-600 !text-sm !font-normal !my-0 !py-0">{__('This is a premium plugin, you may need to buy a license', 'ploogins-ai-assistant')}</span>
                                </div>
                            )
                        }
                        
                        <div className="space-y-2">


                            <div className="flex items-center gap-4 justify-end">
                                <div className="hidden md:!block">
                                    <p className="!text-sm italic !text-neutral-500 !my-0">
                                        {sprintf(
                                            __('This plugin is %s', 'ploogins-ai-assistant'),
                                            isInstalled
                                                ? isActive
                                                    ? __('installed and active', 'ploogins-ai-assistant')
                                                    : __('installed but not active', 'ploogins-ai-assistant')
                                                : __('not installed', 'ploogins-ai-assistant')
                                        )}
                                    </p>
                                </div>

                                <div>
                                    {!isInstalled ? (
                                        <>
                                            {
                                                !isPremiumPlugin && (
                                                    <Button onClick={handleInstallPlugin} disabled={installPlugin.isPending} isPressed={installPlugin.isPending} isBusy={installPlugin.isPending}  __next40pxDefaultSize variant="primary">
                                                        {__('Install', 'ploogins-ai-assistant')}
                                                    </Button>
                                                )
                                            }

                                            {
                                                isPremiumPlugin && (
                                                    <Button className="gap-1" onClick={() => window.open(plugin.homepage, '_blank')} disabled={installPlugin.isPending} isPressed={installPlugin.isPending} isBusy={installPlugin.isPending} __next40pxDefaultSize variant="primary">
                                                        <Icon size={22} icon={external} />
                                                        {__('Buy a license', 'ploogins-ai-assistant')}
                                                    </Button>
                                                ) 
                                            }
                                        </>
                                    ) : !isActive ? (
                                        <>
                                            <Button isBusy={activatePlugin.isPending} onClick={handleActivatePlugin} __next40pxDefaultSize variant="primary">
                                                {__('Activate', 'ploogins-ai-assistant')}
                                            </Button>

                                            <Button isBusy={deletePlugin.isPending} onClick={handleDeletePlugin} variant="tertiary" __next40pxDefaultSize>
                                                {__('Delete', 'ploogins-ai-assistant')}
                                            </Button>
                                        </>
                                    ) : (
                                        <Button isBusy={deactivatePlugin.isPending} onClick={handleDeactivatePlugin} __next40pxDefaultSize variant="secondary">
                                            {__('Deactivate', 'ploogins-ai-assistant')}
                                        </Button>
                                    )}
                                </div>
                            </div>

                            <div className="flex flex-wrap items-start gap-2">
                                <img className="w-12 h-12 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>
                                    <h1 className="!text-lg !py-0 !line-clamp-1" title={decodeEntities(plugin?.name ?? '')}>{decodeEntities(plugin?.name ?? '')}</h1>
                                    <div dangerouslySetInnerHTML={{ __html: plugin?.author?.replace(/href/g, "target='_blank' href") ?? '' }}></div>
                                </div>
                            </div>

                            <div className="flex flex-wrap items-center gap-4">

                                {
                                    !isPremiumPlugin && (
                                        <div className="flex items-center">
                                            {Array.from({ length: 5 }, (_, index) => (
                                                <Icon
                                                    key={index}
                                                    size={20}
                                                    icon={index < Math.round(plugin.rating / 20) ? starFilled : starEmpty}
                                                />
                                            ))}
                                            <span className="!text-xs !font-normal !my-0 !py-0">({plugin.num_ratings})</span>
                                        </div>
                                    )
                                }

                                {
                                    !isPremiumPlugin && (
                                        <a className="border-b border-neutral-500 !text-neutral-500 hover:!text-neutral-800 hover:border-neutral-800" href={`https://wordpress.org/plugins/${plugin?.slug ?? ''}`} target="_blank" rel="noopener noreferrer">
                                            <div className="flex items-center gap-1">
                                                <Icon size={16} icon={external} />
                                                {__('WordPress.org Plugin Page', 'ploogins-ai-assistant')}
                                            </div>
                                        </a>
                                    )
                                }

                                <a className="border-b border-neutral-500 !text-neutral-500 hover:!text-neutral-800 hover:border-neutral-800" href={plugin?.homepage ?? ''} target="_blank" rel="noopener noreferrer">
                                    <div className="flex items-center gap-1">
                                        <Icon size={16} icon={external} />
                                        {__('Plugin Homepage', 'ploogins-ai-assistant')}
                                    </div>
                                </a>
                            </div>
                        </div>

                        {
                            isPluginInsightsPending && (
                                <div className="bg-neutral-50 border border-neutral-200 p-4 rounded-xl h-50 animate-pulse flex items-center justify-center">
                                    <span className="!text-sm !font-medium !my-0 !py-0">{__('Getting AI Insights...', 'ploogins-ai-assistant')}</span>
                                </div>
                            )
                        }

                        {pluginInsights && (
                            <div className="border border-neutral-400 rounded-lg overflow-hidden">
                                <div className="text-center bg-neutral-400 p-1">
                                    <span className="!text-white !text-xs !font-normal !my-0 !py-0">{__('Plugin AI Insights', 'ploogins-ai-assistant')}</span>
                                </div>

                                <div className="p-4 grid grid-cols-1 gap-4">
                                    <div className="flex gap-2 items-start">
                                        <p className="!text-xl italic !font-normal !my-0 !py-0 !font-serif">{pluginInsights.main_purpose}</p>
                                    </div>

                                    <div className="flex flex-wrap items-center gap-2">
                                        <div className={`flex gap-1 items-center px-2 py-1 ${
                                            pluginInsights.complexity_level === 'beginner' ? 'bg-green-50 border border-green-400' :
                                            pluginInsights.complexity_level === 'intermediate' ? 'bg-yellow-50 border border-yellow-400' :
                                            'bg-red-50 border border-red-400'
                                        }`}>
                                            <Icon className={`${
                                                pluginInsights.complexity_level === 'beginner' ? 'fill-green-700' :
                                                pluginInsights.complexity_level === 'intermediate' ? 'fill-yellow-700' :
                                                'fill-red-700'
                                            }`} icon={commentAuthorAvatar} />
                                            <span className={`${
                                                pluginInsights.complexity_level === 'beginner' ? 'text-green-700' :
                                                pluginInsights.complexity_level === 'intermediate' ? 'text-yellow-700' :
                                                'text-red-700'
                                            } capitalize`}>{pluginInsights.complexity_level}</span>
                                        </div>

                                        <div className="flex gap-1 items-center px-2 py-1 bg-green-50 border border-green-400">
                                            <Icon className="fill-green-700" icon={category} />
                                            <span className="text-green-700">{pluginInsights.category}</span>
                                        </div>
                                    </div>

                                    {
                                        pluginInsights.summary && (
                                            <div className="">
                                                <div className="prose max-w-full prose-neutral prose-p:!mt-0 prose-p:!py-0 prose-p:!text-base prose-p:!font-normal prose-p:!text-neutral-700" dangerouslySetInnerHTML={{ __html: autop(pluginInsights.summary) }}></div>
                                            </div>
                                        )
                                    }

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        {
                                            pluginInsights.features?.map((feature: string) => (
                                                <div className="flex items-start gap-2">
                                                    <Icon className="fill-green-700 bg-green-200 rounded-full" size={20} icon={check} />
                                                    <span className="flex-1 min-w-0 !text-sm !font-normal !my-0 !py-0">{feature}</span>
                                                </div>
                                            ))
                                        }
                                    </div>

                                    <div className="flex flex-wrap items-center gap-2">
                                        {pluginInsights.tags?.map((tag: string) => (
                                            <button onClick={() => {
                                                setQuery(tag)
                                                setPlugin(null)
                                                navigate({ to: '/search' })
                                            }} role="button" className="cursor-pointer flex gap-1 items-center px-2 py-1 bg-white border border-neutral-300 hover:border-neutral-700">
                                                <span className="text-neutral-700">{tag}</span>
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        )}

                        <div className="bg-neutral-100 border border-neutral-200 rounded-xl p-2 md:p-4 overflow-hidden space-y-6">
                            <Related />
                            <Activity />
                            <Notes />
                        </div>
            
                    </div>
                )
            }
        </div>
    )
}

export default PluginDetails