import React, { useContext, useEffect, useMemo, useState } from 'react';
import _ from 'lodash';
import { InputBase } from '../components/Input';
import ServiceContext from './ServiceContext';
import useQuery from '../hooks/useQuery';


const ServiceSearch: React.FC = () => {
  const service = useContext(ServiceContext);
  const [search, setSearch] = useState<string>('');
  const { query, setQuery } = useQuery();

  const placeholder = `Искать ${service.name.toLowerCase()}`;

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => setSearch(event.target.value);

  const updateQuery = (value: string) => {
    if (service.searchBy) {
      const newQuery = service.searchBy.reduce((acc, key) => {
        if (value) acc[`${key}[$regex]`] = value;
        else delete acc[`${key}[$regex]`];
        return acc;
      }, query);

      setQuery(newQuery);
    }
  };

  // Debounce updateQuery on search change
  useEffect(() => {
    const handler = setTimeout(() => {
      updateQuery(search);
    }, 300);

    return () => {
      clearTimeout(handler);
    };
  }, [search]);


  // When querySearch changes externally, update search
  const querySearch = useMemo(() => query[`${service.searchBy?.[0]}[$regex]`] || '', [query]);
  useEffect(() => {
    if (querySearch !== search) setSearch(querySearch);
  }, [querySearch]);

  return (
    <div className="mr-6 flex items-center">
      <InputBase placeholder={placeholder} value={search} onChange={handleChange} />
    </div>
  );
};

export default ServiceSearch;
