import React from 'react';
import Icon from '../../../shared/components/icon';
import { TypeaheadOption } from '../../types';
import Spinner from '../../../search-results/components/spinner/spinner';

interface SearchInputProps {
  onChange: (input: string) => void;
  searchResults: TypeaheadOption[];
  onOptionSelect: (val: TypeaheadOption) => void;
  highlightTarget: string;
  label: string;
  isSecondInput?: boolean;
  isDoubleInput?: boolean;
  isDisabled?: boolean;
  isLoading?: boolean;
}

const SearchInput: React.FC<SearchInputProps> = ({
  searchResults,
  onOptionSelect,
  highlightTarget,
  label,
  isSecondInput,
  isDoubleInput,
  isDisabled,
  isLoading
}) => {
  if (isDisabled) {
    return null;
  }
  const highlightMatch = (option: TypeaheadOption, highlight: string) => {
    if (!highlight) {
      return option.value;
    }

    const parts = option.value.split(new RegExp(`(${highlight})`, 'gi'));
    return (
      <span>
        {parts.map((part, index) =>
          part.toLowerCase() === highlight.toLowerCase() ? (
            <span key={index} className="qsm__double-input-option-content--airport">
              {part}
            </span>
          ) : (
            part
          )
        )}
      </span>
    );
  };

  // if (searchResults.length === 0) {
  //   return null;
  // }

  return (
    <div
      className={`qsm__double-input-options${isSecondInput ? ' qsm__double-input-options--second-input' : ''}${
        isDoubleInput ? ' qsm__double-input-options--splittable' : ''
      }`}>
      {isLoading && <Spinner />}
      {searchResults.map((option, index) => (
        <div
          key={index}
          className="qsm__double-input-option"
          onMouseDown={(e) => {
            e.preventDefault();
            e.stopPropagation();
          }}
          onClick={(e) => {
            e.stopPropagation();
            onOptionSelect(option);
          }}
          role="option"
          aria-selected={false}>
          <div className="qsm__double-input-option-content">
            <Icon name={option.type === 'hotel' ? 'ui-hotel' : option.type === 'airport' ? 'ui-flight' : 'ui-location'} height={16} />

            <div className="qsm__double-input-option-content-text">
              {highlightMatch(option, highlightTarget)}
              {option.country && <span className="qsm__double-input-option-content-country">{option.country}</span>}
            </div>
          </div>
          {option.iataCode && <span className="qsm__double-input-option-content-airport-label">[{option.iataCode}]</span>}
        </div>
      ))}
    </div>
  );
};

export default SearchInput;
