import { Combobox, Option } from '@fluentui/react-components';
import { useState } from 'react'
import { setCurrentObjectId, useObjectsStore } from '../../../store/objects';
import useSWR, { SWRConfiguration } from 'swr';
import { useThrottle } from '@uidotdev/usehooks';
import { BASE_URL } from '../../../constants';
import { fetcher } from '../../../http/axiosInstanceNest';

const swrOptions: SWRConfiguration = {
    revalidateOnFocus: false
}

const MapObjectSearch = ({
    map_id
}: {
    map_id: string
}) => {
    const [searchObject, setSearchObject] = useState<string | undefined>("")
    const throttledSearchObject = useThrottle(searchObject, 500)

    const { selectedYear, selectedDistrict } = useObjectsStore().id[map_id]

    const { data: searchData } = useSWR(
        throttledSearchObject !== "" && selectedDistrict && selectedYear ? `/general/search/objects?q=${throttledSearchObject}&id_city=${selectedDistrict}&year=${selectedYear}` : null,
        (url) => fetcher(url, BASE_URL.nest),
        swrOptions
    )

    return (
        <Combobox
            placeholder="Поиск"
            value={searchObject}
            onOptionSelect={(_ev, data) => {
                if (data.optionValue) {
                    setCurrentObjectId(map_id, data.optionValue);
                    setSearchObject(
                        searchData?.find((item: any) => item.id_object.toString() === data.optionValue)?.value ?? ""
                    );
                }
            }}
            onChange={(e) => {
                setSearchObject(e.currentTarget.value); // free typing like Mantine's onChange
            }}
            clearable
            style={{ minWidth: 'auto' }}
        >
            {searchData
                ? searchData.map((item: { value: string; id_object: string }) => (
                    <Option key={item.id_object} value={item.id_object.toString()}>
                        {item.value}
                    </Option>
                ))
                : null}
        </Combobox>
    )
}

export default MapObjectSearch