import { ElementType, useState } from 'react';
import { createSearchParams, useNavigate } from 'react-router-dom';
import { IndexSignature } from '../../utils';

export const WithHocSearch = (Component: ElementType) => {
  return function WithHocSearchComponent({ ...props }: IndexSignature) {
    const [search, setSearch] = useState<string>('');
    const navigate = useNavigate();

    return (
      <Component
        handleSearch={({ target }: any) => setSearch(target.value)}
        handleSearchTrigger={(e: any, path?: string) => {
          e.preventDefault();
          setSearch(e.currentTarget.elements[0].value);

          if (path) {
            navigate({
              pathname: path,
              search: createSearchParams({
                search: search,
              }).toString(),
            });
          }
        }}
        filterData={(data: any[]) => {
          return data.filter(datum => {
            let searchableDatum: string[] = [];

            Object.keys(datum).slice(1).forEach(attribute => {
              searchableDatum.push(String(datum[attribute]));
            });

            return searchableDatum.join(' ').toLowerCase()
              .indexOf(search.toLowerCase()) >= 0;
          });
        }}
        {...props}
      />
    );
  };
};

export type HandleSearchType = ({ target }: any) => void;
export type HandleSearchTriggerType = (e: any) => void;
export type FilterDataType = (data: any[]) => any[];
