import { Select } from 'antd';
import { electronicsSubCats } from 'apiCalls/apiEndpoints';
import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react'
import { useQuery } from 'react-query';
import { SyncLoader } from 'react-spinners';
import { isEmpty } from 'utilFuncs/utilFunctions';

const { Option } = Select;

function EducationFiltersMobile() {

    const router = useRouter();
    const [queryObj, setqueryObj] = useState<any>({})

    //get the categories
    const { data, isSuccess, isLoading } = useQuery(['electronics-filter-fields'], electronicsSubCats, {
        refetchOnWindowFocus: false
    });

    //set the electronics category
    const [electronics, setElectronicsCate] = useState<any>([])

    useEffect(() => {
        if (isSuccess) {
            setElectronicsCate(data?.data.data.subclassifieds)
        }
    }, [data?.data.data.subclassifieds, isSuccess])

    useEffect(() => {
        if (!isEmpty(queryObj)) {
            router.push({
                pathname: 'electronics',
                query: queryObj
            })
        }
    }, [queryObj]);

     //when a category is selected
     const onChange = (value: string) => {
        setqueryObj((prev: any) => {
            return { ...prev, 'type': value }
        })
    };

    //when a search query is made
    const onSearch = (value: string) => {
        console.log('search:', value);
    };

    return (
        <>{isLoading ? <div className='overflow-hidden center'>
            <SyncLoader color='green' size={5} />
        </div> : <Select
            showSearch
            placeholder={isLoading ? 'loading, please wait' : "Select a category"}
            optionFilterProp="children"
            className='w-full'
            onChange={onChange}
            onSearch={onSearch}
            disabled={isLoading}
            filterOption={(input, option) =>
                (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
            }
        >
            {electronics.map((sbc: any) => (
                <Option key={sbc.id} value={sbc.slug}>{sbc.name}</Option>
            ))}
        </Select>}

        </>
    )
}

export default EducationFiltersMobile