import { debounce } from 'lodash-es';
import React, { useEffect, useRef } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { CloseIcon, SearchIcon } from '@/icons';
import { MAX_SEARCH_TERM_LEN } from '@/utils/constants';

// TODO: abstract this and passing in props so it's reusable
const SearchInput = () => {
  const searchInputRef = useRef<HTMLInputElement>(null);

  // focus on search input when it is shown
  useEffect(() => {
    searchInputRef?.current?.focus();
  }, []);
  const { search } = useStores();

  const debounceSearchTerm = debounce((e) => {
    const term = e.target.value.trim().substring(0, MAX_SEARCH_TERM_LEN);
    search.searchTerm = term;
  }, 400);

  return (
    <div
      className={'flex w-full flex-row rounded-full bg-background-secondary'}
    >
      <div className='flex flex-row items-center justify-center pl-6'>
        <SearchIcon className='h-4 w-4 text-foreground-primary' />
      </div>
      <input
        className={
          'w-full border-none bg-transparent p-4 placeholder-foreground-secondary outline-none'
        }
        ref={searchInputRef}
        defaultValue={search.searchTerm}
        placeholder={'Search for songs, playlists, users, or genres'}
        onChange={debounceSearchTerm}
      />
      {search.searchTerm && (
        <div className='flex flex-row items-center justify-end pr-3'>
          <Button
            variant={ButtonVariant.Glass}
            size={ButtonSize.Mini}
            shape={ButtonShape.Pill}
            onClick={() => {
              search.searchTerm = '';
              if (searchInputRef.current) {
                searchInputRef.current.value = '';
                searchInputRef.current.focus();
              }
            }}
            iconStart={CloseIcon}
            className='px-1.5 py-1.5'
          />
        </div>
      )}
    </div>
  );
};

export default SearchInput;
