import { IoIosSearch } from "react-icons/io";
import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";

const Search = () => {
    const navigate = useNavigate();
    const [searchTerm, setSearchTerm] = useState('');
    const handleSubmit = (e) => {
        e.preventDefault();
        const urlParams = new URLSearchParams(window.location.search);
        urlParams.set('searchTerm', searchTerm);
        const searchQuery = urlParams.toString();
        navigate(`/search?${searchQuery}`);
    };
    useEffect(() => {
        const urlParams = new URLSearchParams(location.search);
        const searchTermFormUrl = urlParams.get('searchTerm');
        if(searchTermFormUrl){
        setSearchTerm(searchTermFormUrl);
        }
    }, [location.search])
  return (
    <form onSubmit={handleSubmit} className="text-black mt-5 bg-white flex items-center border border-blue-800 rounded-md">
        <input type="text" placeholder="Search your dream property" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="px-4 py-2 focus:outline-none bg-transparent text-sm w-60 sm:w-80"/>
        <button>
            <IoIosSearch className="text-slate-600 text-lg m-2"/>
        </button>
    </form>
  )
}

export default Search