import React, { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames/bind';
import { CSSTransition } from 'react-transition-group';
import { config } from 'config/general';
import { animationClassList } from 'store/utils/view';
import styleIdentifiers from './imageGallery.scss';
import previousBtn from './assets/previous.svg';
import nextBtn from './assets/next.svg';
import closeBtn from './assets/closeModal.svg';

const styles = classNames.bind(styleIdentifiers);

export interface ImageGalleryProps {
  dialogHide: Function;
  images: string[];
  current: number;
  active: boolean;
}

const ImageGallery = (props: ImageGalleryProps) => {
  const { images, current, active, dialogHide } = props;

  const [imageIndex, setImageIndex] = useState(current);

  const next = () => {
    const nextIndex = imageIndex + 1 < images.length ? imageIndex + 1 : 0;
    setImageIndex(nextIndex);
  };

  const previous = () => {
    const previousIndex = imageIndex - 1 >= 0 ? imageIndex - 1 : images.length - 1;
    setImageIndex(previousIndex);
  };

  const close = () => {
    dialogHide('custom');
  };

  useEffect(() => {
    const keyHandler = event => {
      if (event.key === 'ArrowLeft') previous();
      else if (event.key === 'ArrowRight') next();
    };
    // to be sure
    document.removeEventListener('keydown', keyHandler);
    document.addEventListener('keydown', keyHandler);
    return () => {
      document.removeEventListener('keydown', keyHandler);
    };
  }, [imageIndex]);

  return ReactDOM.createPortal(
    <CSSTransition
      in={active}
      timeout={config.timeoutDialog}
      appear
      unmountOnExit
      classNames={animationClassList('image-gallery', styles)}
    >
      <div className={styles('image-gallery')}>
        <div className={styles('image-preview')}>
          <img src={images[imageIndex]} alt={`preview-${imageIndex}`} />
        </div>
        <div className={styles('image-gallery-btn')}>
          {images.length > 1 && (
            <>
              <div className={styles('prev')} onClick={previous}>
                <img src={previousBtn} alt="previous" />
              </div>
              <div className={styles('next')} onClick={next}>
                <img src={nextBtn} alt="next" />
              </div>
            </>
          )}
          <div className={styles('close')} onClick={close}>
            <img src={closeBtn} alt="close" />
          </div>
        </div>
      </div>
    </CSSTransition>,
    document.body,
  );
};

export default ImageGallery;
