import React, { useRef, useEffect, MutableRefObject } from 'react';

import Button from '../Button';
import Portal from '../Portal';

import {
  Wrapper, InputWrapper, Input, ResultInfo, ArrowButton,
} from './styled';

type Props = {
  matchesTotal: number;
  matchIndex: number;
  onEnter: (val: string) => void;
  onPrev: () => void;
  onNext: () => void;
  isActive?: boolean;
  close: () => void;
};

const Search: React.FunctionComponent<Props> = ({
  matchesTotal = 0,
  matchIndex = 1,
  onPrev,
  onNext,
  onEnter,
  isActive = false,
  close,
}: Props) => {
  const inputRef = useRef(null) as MutableRefObject<any>;

  const handleKeyDown = (e: React.KeyboardEvent): void => {
    if (e.keyCode === 13 && inputRef.current.value) {
      onEnter(inputRef.current.value);
    }
  };

  useEffect(() => {
    if (isActive) {
      inputRef.current.focus();
    }
  }, [isActive]);

  return (
    <Portal>
      <Wrapper open={isActive}>
        <InputWrapper>
          <Input ref={inputRef} onKeyDown={handleKeyDown} />
          <ResultInfo>
            {matchesTotal ? `${matchIndex + 1} / ${matchesTotal}` : ''}
          </ResultInfo>
        </InputWrapper>
        <ArrowButton variant="top" onClick={onPrev} />
        <ArrowButton variant="bottom" onClick={onNext} />
        <Button appearance="primary" style={{ marginLeft: '16px' }} onClick={close}>Close</Button>
      </Wrapper>
    </Portal>
  );
};

export default Search;
