import { FC, useRef, useState } from "react";
import RightArrow from 'public/icons/right-arrow.svg';
import styles from './gallery.module.scss';

interface Gallery {
  title?: string;
  description: string;
  images: string[];
  offset: number;
}

const GalleryComponent: FC<Gallery> = ({ title, description, images, offset }) => {
  const imageContainer = useRef(null);
  const [isDown, setIsDown] = useState(false);
  const [startX, setStartX] = useState(0);
  const [scrollLeft, setScrollLeft] = useState(0);
  
  const onMouseDown = (event) => {
    setIsDown(true);
    setStartX(event.pageX - imageContainer.current.offsetLeft);
    setScrollLeft(imageContainer.current.scrollLeft);
  };

  const onMouseOut = () => {
    setIsDown(false);
  };
  
  const onMouseMove = (event) => {
    if (!isDown) return;
    event.preventDefault();
    const x = event.pageX - imageContainer.current.offsetLeft;
    const walk = (x - startX) * 3;
    imageContainer.current.scrollLeft = scrollLeft - walk;
  };

  return (
    <div className={styles.gallery}>
      {title && <div className={styles.galleryTitle} style={{marginLeft: offset}}>
        <span>{title}</span> 
      </div>}
      <div className={styles.galleryInfo} style={{marginLeft: offset, marginRight: offset}}>
        <div className={styles.galleryDescription}>
          <p>{description}</p>
        </div>
        <div className={styles.galleryArrow}>
          scroll
          <span>
            <RightArrow />
          </span>
        </div>
      </div>
      {images && <div className={styles.galleryImages}>
        <div ref={imageContainer} onMouseMove={onMouseMove} onMouseDown={onMouseDown} onMouseLeave={onMouseOut} onMouseUp={onMouseOut}>
          {images.map((image, index) => (
            <div className={styles.galleryImagesItem} key={index} style={{marginLeft: index === 0 ? offset + 12 : 0}}>
              <img src={image} alt=""/>
            </div>
          ))}
        </div>
      </div>}
    </div>
  );
};

export default GalleryComponent;