import { useQuery, useQueryClient } from "@tanstack/react-query"
import { __ } from "@wordpress/i18n"
import { Link } from "@tanstack/react-router"
import { getGroupQueryOptions, getGroupsQueryOptions } from "@/shared/ploogins-groups/query-options"

const GroupsGrid = () => {

    const { data, isPending } = useQuery(getGroupsQueryOptions())

    if (isPending) {
        return <div className="bg-white p-4 rounded-xl h-50 animate-pulse flex items-center justify-center">
            <span className="!text-sm !font-medium !my-0 !py-0">{__('Getting Groups...', 'ploogins-ai-assistant')}</span>
        </div>
    }

    const queryClient = useQueryClient()

    const handleGorupHover = (group: PlooginsGroup) => {
        queryClient.prefetchQuery(getGroupQueryOptions(group.uuid))
    }

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

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {data?.map((group) => (
                    <Link to="/group/$uuid" onMouseEnter={() => handleGorupHover(group)} params={{ uuid: group.uuid }} key={group.slug} className="bg-white border border-neutral-200 p-4 rounded-xl space-y-4 hover:border-neutral-700" title={group.name}>

                        <div className="flex items-start gap-4">
                            <img src={group.icon} alt={group.name} className="w-12 h-12 object-contain rounded-lg" />

                            <div className="flex-1 grid grid-cols-1 gap-2">

                                <div>
                                    <h2 className="!text-base !font-normal !my-0 !py-0 !line-clamp-1 flex-1 min-w-0">{group.name}</h2>

                                    <p className="!text-xs !text-neutral-500 !my-0 !py-0">{group.service_name}</p>
                                </div>

                                <div className="flex items-center gap-2">
                                    <span className="bg-neutral-200 px-2 py-1 capitalize rounded !text-xs !text-neutral-800 !my-0">{group.type}</span>
                                    <p className="!text-xs !text-neutral-500 !my-0 !py-0">{group.items_count} {__('items', 'ploogins-ai-assistant')}</p>
                                </div>
                            </div>
                        </div>

                        <div>
                            <p className="!text-xs !text-neutral-500 !my-0 !py-0">{group.description}</p>
                        </div>
                    </Link>
                ))}
            </div>
        </div>
    )
}

export default GroupsGrid