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

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

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

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

const Search: React.FC<Props> = ({
  matchesTotal = 0,
  current = 0,
  onPrev,
  onNext,
  onEnter,
  isActive = false,
  isProcessing = false,
  close,
}: Props) => {
  const { t } = useTranslation('toolbar');
  const inputRef = useRef() as MutableRefObject<HTMLInputElement>;

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

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

  return (
    <Portal>
      <Wrapper open={isActive}>
        <InputWrapper>
          <Input
            ref={inputRef}
            placeholder={t('searchDocument')}
            onKeyDown={handleKeyDown}
          />
          <ResultInfo>
            {isProcessing ? (
              <LoadingWrapper>
                <Loading />
              </LoadingWrapper>
            ) : (
              ''
            )}
            {matchesTotal ? `${current} / ${matchesTotal}` : ''}
          </ResultInfo>
        </InputWrapper>
        <ArrowButton variant="top" onClick={onPrev} />
        <ArrowButton variant="bottom" onClick={onNext} />
        <Button
          appearance="primary"
          style={{ marginLeft: '16px' }}
          onClick={close}
        >
          {t('close')}
        </Button>
      </Wrapper>
    </Portal>
  );
};

export default Search;
