/* eslint-disable react/no-array-index-key */
/* eslint-disable react/forbid-prop-types */
import React, { useRef, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import ScrollX from 'gatsby-core-theme/src/hooks/scroll-x';
import Item from './item';
import Buttons from './buttons';

const CustomCarousel = ({ page, module, noModuleIntro }) => {
  const container = useRef(null);
  const [scrollX, setScrollX] = useState(0);
  const [scrollEnd, setScrollEnd] = useState(false);
  const [showButtons, setShowButtons] = useState(false);

  const updateButtons = (shift) => {
    setScrollEnd(
      Math.floor(container.current.scrollWidth - (container.current.scrollLeft + shift)) <=
        container.current.offsetWidth
    );
  };

  const scroll = (shift) => {
    container.current.scrollTo({
      left: container.current.scrollLeft + shift,
      behavior: 'smooth',
    });
    updateButtons(shift);
    setScrollX(scrollX + shift);
  };

  const onStopScrolling = () => {
    setScrollX(container.current.scrollLeft);
    updateButtons(0);
  };

  const onScroll = (scrollLeft) => {
    updateButtons(0);
    setScrollX(scrollLeft);
  };

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowButtons(container.current.scrollWidth > container.current.offsetWidth);
    }, 500);
    return () => clearTimeout(timer);
  }, []);

  return (
    <ScrollX refTag={container} scroll stopScrolling={() => onStopScrolling()} onScroll={onScroll}>
      <div ref={container}>
        {module.items &&
          module.items.map((item, index) => (
            <Item key={index} index={index} item={item} page={page} module={module} />
          ))}
        {showButtons && (
          <Buttons
            scroll={scroll}
            noModuleIntro={noModuleIntro}
            scrollX={scrollX}
            scrollEnd={scrollEnd}
          />
        )}
      </div>
    </ScrollX>
  );
};

CustomCarousel.propTypes = {
  page: PropTypes.shape({}),
  module: PropTypes.shape({
    items: PropTypes.arrayOf(PropTypes.object),
    style: PropTypes.string,
  }).isRequired,
  noModuleIntro: PropTypes.bool,
};

export default CustomCarousel;
