import { useDistricts } from 'context/DistrictContext'
import { url } from 'inspector'
import { useRouter } from 'next/router'
import React, { useState } from 'react'
import bg from 'assets/images/main.jpg'
import pp from 'public/main-side-right.png'
import nbg from 'assets/images/main-bg-image.png'
import Image from 'next/image'
import Link from 'next/link'
import { useMutation, useQuery } from 'react-query'
import { searchQuery } from 'apiCalls/apiEndpoints'
import { SyncLoader } from 'react-spinners'

function SearchComp() {
    const { currentDistrict } = useDistricts()
    const router = useRouter()

    const [showSuggestion, setshowSuggestion] = useState<boolean>(false)
    const [query, setQuery] = useState<string>('');
    const [queryRes, setQueryRes] = useState<any>([]);

    //search user
    const { mutate, isLoading } = useMutation(searchQuery, {
        onSuccess: data => {
            setQueryRes(data.data)
            if (data.data?.length > 0) {
                if (data.data.length > 0) {
                    setshowSuggestion(true);
                }else {
                    setshowSuggestion(false);
                }
            }
        },
        onError: err => {
            console.log('query err', err);
        }
    })

    //search user using use query
    const {data} = useQuery([]);

    //


    //handle search input change
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // console.log(e.target.value)
        if (e.target.value.length > 0) {
            setQuery(e.target.value);
            mutate(e.target.value);
        } else {
            setshowSuggestion(false)
            setQueryRes([])
        }

        if(e.target.value === ''){
            setshowSuggestion(false)
            setQueryRes([])
        }
    }

    //this is getting complicated
    const handleMouseDown = () => {
        // if (window.innerWidth <= 723) {
        //     router.push('/search')
        // }
    }

    const styling = {
        backgroundImage: `url(${bg.src})`,
        
    }

    //when the enter key is pressed
    const handleKeyDown = (e: any) => {
        const key = e.keyCode || e.which;
        if (key === 13 && e.target.value.length > 1) {
            setQuery(e.target.value)
            router.push(`/search?query=${e.target.value}`)
        }else {
            setQuery(e.target.value)
        }
    }

    const handleSearchClicked = () => {
        if(query.length > 1){
            router.push(`/search?query=${query}`)
        }
    }

    const handleBlur = () => {
        // setshowSuggestion(false)
        // setQuery('');
    }

    return (
        <section className="search-comp-start w-full bg-white h-[299px] flex flex-col items-center justify-center] pt-14 relative" style={styling}>
            <div className='w-[313px] h-[270px] hidden lg:block mt-6 mr-6 absolute top-0 right-0'>
                <Image src={pp.src} layout="fill"  alt='for everyone' /> 
            </div>

            <div className="header-caption" style={{ fontSize: '27px' }}>
                <h1 className='text-2xl text-white text-center'>Top Listings In {currentDistrict !== null ? currentDistrict : 'Ashanti'}</h1>
                {/* <div className="header-caption" style={{ fontSize: '27px' }}><h1>Top Listings In Ashanti</h1></div> */}
            </div>

            <div className='relative'>
                <div className='header-form relative mt-3'>
                    <input onMouseDown={handleMouseDown} onChange={handleChange} onKeyDown={handleKeyDown} onBlur={handleBlur} type="text" placeholder='search anything' className='w-[350px] sm:w-[500px] md:w-[600px] lg:w-[750px] h-12 p-3  rounded-full text-gray-600 font-italic' />
                    <svg xmlns="http://www.w3.org/2000/svg" onClick={handleSearchClicked} className="h-6 w-6 absolute top-3 right-2 cursor-pointer" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M8 16l2.879-2.879m0 0a3 3 0 104.243-4.242 3 3 0 00-4.243 4.242zM21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                </div>
                <div className={`suggestions relative sm:w-[500px] md:w-[600px] lg:w-[750px] ${showSuggestion && query.length > 0 ? 'block' : 'hidden'}`}>
                    <ul className='w-full z-10 absolute rounded-md h-96 overflow-auto'>
                        {isLoading && ( <div className='text-center'><SyncLoader color='green' size={5} /></div> )}
                        <Link href={`/search?query=${query}`}>
                            <li className='z-10 bg-white font-normal shadow-xl text-gray-500 py-3 drop-shadow-md pl-2 cursor-pointer hover:bg-gray-500 '>{query}</li>
                        </Link>
                        {queryRes?.length > 0 ? queryRes?.map((opt: any, index: any) => (
                                <Link href={`/search?query=${opt.name}`} key={index}>
                                    <li className='z-10 bg-white font-normal shadow-xl text-gray-500 py-3 drop-shadow-md pl-2 cursor-pointer hover:bg-gray-500'>{opt?.name}</li>
                                </Link>
                        )) : ''}
                    </ul>
                </div>
            </div>
            <div className='header-location d-flex mt-6'>
                <p className='text-white text-sm flex'>Find Ads in all of <button className='bg-green-800 px-2 ml-2 flex items-center'><svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg> {currentDistrict !== null ? currentDistrict : 'Ashanti'}</button></p>
            </div>

        </section>
    )
}

export default SearchComp