import React, { forwardRef, useRef } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Icon } from '../../atoms/icon/Icon';

const propTypes = {
  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,
  className: PropTypes.string,
  placeholder: PropTypes.string,
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  disabled: PropTypes.bool,
  isLoading: PropTypes.bool,
  isInline: PropTypes.bool,
  onChange: PropTypes.func,
  resultsLength: PropTypes.number,
  value: PropTypes.string,
};

const defaultProps = {
  tag: 'div',
  className: '',
  placeholder: 'Search...',
  defaultClassName: 'sui-m-search-bar',
  disabled: false,
  isLoading: false,
  isInline: false,
  onChange: () => {},
  resultsLength: null,
  value: '',
};

export const SearchBar = forwardRef(({
  tag: Tag,
  defaultClassName,
  className,
  placeholder,
  disabled,
  isLoading,
  isInline,
  onChange,
  resultsLength,
  value,
  ...attributes
}, ref) => {
  const searchInputRef = ref || useRef(undefined);

  const classes = classnames(
    defaultClassName,
    isLoading ? 'as--loading' : '',
    isInline ? 'as--inline' : '',
    className
  );

  const handleChange = (targetValue) => {
    onChange(targetValue);

    if (searchInputRef) {
      searchInputRef.current.focus();
    }
  };

  const withResultClassName = () => {
    if (value && resultsLength > 0) {
      return 'as--with-results';
    }

    if (value && resultsLength === 0) {
      return 'as--without-results';
    }

    return '';
  };

  return (
    <Tag className={`${classes} ${withResultClassName()}`} {...attributes}>
      <span className="sui-m-search-bar__icon">
        <Icon name="search" />
      </span>
      {value && (
        <button type="button" className="sui-m-search-bar__clear" onClick={() => handleChange('')}>
          &times;
        </button>
      )}
      <input
        className="sui-a-form-control"
        type="search"
        placeholder={placeholder}
        onKeyDown={(event) => { if (event.key === 'Escape') { handleChange(''); } }}
        onChange={(event) => handleChange(event.target.value)}
        value={value}
        disabled={disabled}
        ref={searchInputRef}
      />
    </Tag>
  );
});

SearchBar.propTypes = propTypes;
SearchBar.defaultProps = defaultProps;
