import SearchInput from "../SearchInput"
import SuggestedSearches from "../SuggestedSearches"
import { useSearch } from "@/hooks/useSearch"
import { Icon } from "@wordpress/components"
import { search } from "@wordpress/icons"
import { __ } from "@wordpress/i18n"
import PluginsView from "../PluginsView"
import { useEffect } from "@wordpress/element"
import usePluginsViewStore from "@/stores/pluginsViewStore"

const Search = () => {

    const { query, data, isFetching } = useSearch()

    const { setData, setIsPending } = usePluginsViewStore()

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

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

    return (
        <>
            {(data || isFetching) ? (
                <div className="h-full flex flex-col">

                    <header style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0' }} className="sticky top-0 bg-white z-10 flex justify-between items-center">
                        <div className="flex items-center gap-2">
                            <Icon icon={search} />
                            <h2 className="!text-lg !font-medium !py-0 !my-0">{query}</h2>
                        </div>

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

                    <PluginsView />
                </div>
            ) : (
                <div className="py-20">
                    <SearchInput size="medium" />
                    <SuggestedSearches />
                </div>
            )}
        </>
    )
}

export default Search