import { useEffect, useState, type FC } from 'react'
import Input from '../../components/Input'
import { useTranslation } from 'react-i18next'
import { useGetServiceSearch } from '../../pages/service/hooks/useServiceData'
import { ServiceType } from '../../pages/service/types/ServiecTypes'
import { Link } from 'react-router-dom'
import { Pages } from '../../config/Pages'
import { useOutsideClick } from '../../hooks/useOutSideClick'

const Search: FC = () => {

    const { t } = useTranslation('global')
    const [search, setSearch] = useState<string>('')
    const [showSearch, setShowSearch] = useState<boolean>(false)
    const { data } = useGetServiceSearch(search)
    const ref = useOutsideClick(() => {
        setShowSearch(false)
    })

    useEffect(() => {

        if (data?.data && data?.data?.services?.length) {
            setShowSearch(true)
        } else {
            setShowSearch(false)
        }

    }, [data])


    return (
        <div className='min-w-[270px] relative hidden xl:block'>
            <Input
                variant='search'
                placeholder={t('header.search')}
                onChangeSearchFinal={setSearch}
            />

            {
                showSearch &&
                <div ref={ref} className='absolute shadow bg-white top-[100%] rounded-xl right-0 w-[270px] p-4 flex flex-col gap-4 overflow-y-auto max-h-screen'>
                    {
                        data?.data?.services?.map((item: ServiceType) => {
                            return (
                                <Link onClick={() => setShowSearch(false)} to={Pages.services.detail + item.slug} key={item.id} className='flex gap-3 items-center border-b pb-4'>
                                    <img src={item.icon} className='size-8 rounded-lg' />
                                    <div className='text-[13px]'>{item.name}</div>
                                </Link>
                            )
                        })
                    }
                </div>
            }
        </div>
    )
}

export default Search