import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom";
import ListingCard from "../components/ListingCard";


const SearchProperties = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [showMore, setShowMore] = useState(false);
    const [listings, setListings] = useState([]);
    const [sidebarSearch, setSidebarSearch] = useState({
        searchTerm: '',
        type: 'all',
        parking: false,
        offer: false,
        furnished: false,
        sort: 'created_at',
        order: 'desc',
    });
    useEffect(() => {
        const urlParams = new URLSearchParams(location.search);
        const searchTermFromUrl = urlParams.get('searchTerm');
        const typeFromUrl = urlParams.get('type');
        const parkingFromUrl = urlParams.get('parking');
        const furnishedFromUrl = urlParams.get('furnished');
        const offerFromUrl = urlParams.get('offer');
        const sortFromUrl = urlParams.get('sort');
        const orderFromUrl = urlParams.get('order');
        if(searchTermFromUrl || typeFromUrl || parkingFromUrl || furnishedFromUrl || offerFromUrl || sortFromUrl || orderFromUrl){
            setSidebarSearch({
                searchTerm: searchTermFromUrl || '',
                type: typeFromUrl || 'all',
                parking: parkingFromUrl === 'true' ? true : false,
                furnished: furnishedFromUrl === 'true' ? true : false,
                offer: offerFromUrl === 'true' ? true : false,
                sort: sortFromUrl || 'created_at',
                order: orderFromUrl || 'desc',
            });
        }
        const fetchListings = async () => {
            setLoading(true);
            setShowMore(false)
            const searchQuery = urlParams.toString();
            const res = await fetch(`/server/listing/get?${searchQuery}`);
            const data = await res.json();
            if(data.length > 11){
                showMore(true);
            } else{
                setShowMore(false);
            }
            setListings(data);
            setLoading(false);
        };
        fetchListings();

    }, [location.search])

    //Search by...
    const handleChange = (e) => {
        if(e.target.id === 'all' || e.target.id === 'rent' || e.target.id === 'sale'){
            setSidebarSearch({...sidebarSearch, type: e.target.id});
        }
        if(e.target.id === 'searchTerm'){
            setSidebarSearch({...sidebarSearch, searchTerm: e.target.value});
        }
        if(e.target.id === 'parking' || e.target.id === 'furnished' || e.target.id === 'offer'){
            setSidebarSearch({...sidebarSearch, [e.target.id]: e.target.checked || e.target.checked === 'true' ? true : false,});
        }
        if(e.target.id === 'sort_order') {
            const sort = e.target.value.split('_')[0] || 'created_at';
            const order = e.target.value.split('_')[1] || 'desc';
            setSidebarSearch({ ...sidebarSearch, sort, order });
        }
    };

    //Submit form
    const handleSubmit = (e) => {
        e.preventDefault();
        const urlParams = new URLSearchParams();
        urlParams.set('searchTerm', sidebarSearch.searchTerm);
        urlParams.set('type', sidebarSearch.type);
        urlParams.set('parking', sidebarSearch.parking);
        urlParams.set('furnished', sidebarSearch.furnished);
        urlParams.set('offer', sidebarSearch.offer);
        urlParams.set('sort', sidebarSearch.sort);
        urlParams.set('order', sidebarSearch.order);
        const searchQuery = urlParams.toString();
        navigate(`/search?${searchQuery}`);
    };

    //show more functionality
    const onShowMore = async () => {
        const numberOfListings = listings.length;
        const startIndex = numberOfListings;
        const urlParams = new URLSearchParams(location.search);
        urlParams.set('startIndex', startIndex);
        const searchQuery = urlParams.toString();
        const res = await fetch(`/server/listing/get?${searchQuery}`);
        const data = await res.json();
        if (data.length < 12) {
        setShowMore(false);
        }
        setListings([...listings, ...data]);
    }


  return (
    <div className="flex flex-col lg:flex-row">
        <div className="p-8 border-b-2 md:border-r-2 lg:min-h-screen">
            <form onSubmit={handleSubmit} className="flex flex-col gap-5">
                <div className="flex items-center gap-2">
                    <label className="whitespace-nowrap font-semibold text-blue-900">Search: </label>
                    <input type="text" id="searchTerm" placeholder="Search your dream property" value={sidebarSearch.searchTerm} onChange={handleChange} className="border rounded-md p-2 w-full text-sm"/>
                </div>
                <div className="flex gap-2 flex-wrap items-center">
                    <label className="whitespace-nowrap font-semibold text-blue-900">Type: </label>
                    <div className="flex gap-2">
                        <input type='checkbox' onChange={handleChange} checked={sidebarSearch.type === 'all'} id="all" className="w-4"/>
                        <span className="text-sm">Rent & Sale</span>
                    </div>
                    <div className="flex gap-2">
                        <input type='checkbox' onChange={handleChange} checked={sidebarSearch.type === 'rent'} id="rent" className="w-4"/>
                        <span className="text-sm">Rent</span>
                    </div>
                    <div className="flex gap-2">
                        <input type='checkbox' onChange={handleChange} checked={sidebarSearch.type === 'sale'} id="sale" className="w-4"/>
                        <span className="text-sm">Sale</span>
                    </div>
                    <div className="flex gap-2">
                        <input type='checkbox' onChange={handleChange} checked={sidebarSearch.offer} id="offer" className="w-4"/>
                        <span className="text-sm">Offer</span>
                    </div>
                </div>

                <div className="flex gap-2 flex-wrap items-center">
                    <label className="whitespace-nowrap font-semibold text-blue-900">Amenities: </label>
                    <div className="flex gap-2">
                        <input type='checkbox' onChange={handleChange} checked={sidebarSearch.parking} id="parking" className="w-4"/>
                        <span className="text-sm">Garage</span>
                    </div>
                    <div className="flex gap-2">
                        <input type='checkbox' onChange={handleChange} checked={sidebarSearch.furnished} id="furnished" className="w-4"/>
                        <span className="text-sm">Furnished</span>
                    </div>
                </div>

                <div className="flex items-center gap-2">
                    <label className="whitespace-nowrap font-semibold text-blue-900">Sort: </label>
                    <select onChange={handleChange} defaultValue={'created_at_desc'} id="sort_order" className="border rounded-md p-1 text-sm">
                        <option value='currentPrice_desc'>Price hight to low</option>
                        <option value='currentPrice_asc'>Price low to hight</option>
                        <option value='createdAt_desc'>Latest</option>
                        <option value='createdAt_asc'>Oldest</option>
                    </select>
                </div>
                <button className="bg-blue-950 text-white font-semibold p-1 rounded-md hover:opacity-95">Search</button>
            </form>
        </div>
        <div className="flex-2">
            <h1 className="text-2xl font-semibold border-b p-8 text-blue-900 capitalize">Listing results</h1>
            <div className="flex flex-wrap p-8 gap-4">
                {!loading && listings.length === 0 &&(
                    <p className="text-red-700 text-md font-semibold tracking-wider capitalize ">No listing found</p>
                )}
                {loading && (
                    <p className="text-blue-900 text-md font-semibold tracking-wider capitalize text-center w-full">loading...</p>
                )}
                {!loading && listings && listings.map((listing) => (<ListingCard key={listing._id} listing={listing}/>))}
                
                {showMore &&(
                    <button onClick={onShowMore} className="w-full text-center text-blue-900 hover:underline p-10">Show more</button>
                )}
            </div>
        </div>
    </div>
  )
}

export default SearchProperties