/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import * as styled from 'styled-components';
import {JSX, useState, useEffect, ChangeEvent} from 'react';
import moment from 'moment';
import {IInput} from './Input';
import Input from './Input';
import Theme from 'theme';
import searchImage from 'assets/images/search-150x150.png';

const searchWaitTimeout = moment.duration(1, 'seconds').asMilliseconds();

interface ISearchInput extends IInput {
  search: (str: string) => void;
  defaultValue?: string;
  minLengthForSearch?: number;
}

const SearchInput = styled.default(Input)`
  min-width: 100%;
  padding-left: ${Theme.spacing.xlarge};
`;

export const SearchInputWrapper = styled.default.div`
  position: relative;
  display: flex;
  & div {
    width: 100%;
    position: relative;
    align-self: center;
    & img {
      width: 1rem;
      height: 1rem;
      top: 50%;
      transform: translateY(-50%);
      left: 0.5rem;
      position: absolute;
    }
  }
`;

export const Search = ({
  search,
  defaultValue = '',
  minLengthForSearch = 2
}: ISearchInput): JSX.Element => {
  const [currentSearchTerm, setCurrentSearchTerm] = useState<string>(defaultValue);
  const onChange = (event: ChangeEvent<HTMLInputElement>): void => {
    setCurrentSearchTerm(event.target.value);
  };

  useEffect(() => {
    let timeout = null;

    if (currentSearchTerm.length >= minLengthForSearch || currentSearchTerm.length === 0) {
      timeout = setTimeout(() => search(currentSearchTerm), searchWaitTimeout);
    }

    return () => {
      if (timeout) {
        clearInterval(timeout);
      }
    };
  }, [currentSearchTerm, minLengthForSearch, search]);

  return (
    <SearchInputWrapper>
      <div className="search-bar">
        <img src={searchImage} alt={'searchImage'} />
        <SearchInput value={currentSearchTerm} onChange={onChange} name="testId-search" />
      </div>
    </SearchInputWrapper>
  );
};

export default Search;