/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';

import Slide from '~molecules/carousel/default-slide';
import keygen from '~helpers/keygen';
import ScrollX from '~hooks/scroll-x';
import styles from './template-two.module.scss';

const Carousel = ({ module = {}, gtmClass = '' }) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const container = useRef(null);
  const scroll = (shift) => {
    container.current.scrollTo({
      left: container.current.scrollLeft + shift,
    });
  };

  return (
    <div className={styles.container}>
      <Slide
        slideTitle={`${module?.title}-carousel-main`}
        item={module?.items[activeIndex]}
        gtmClass={gtmClass}
      />
      <ScrollX refTag={container} scroll={scroll}>
        <div ref={container} className={styles.carouselContainer || ''}>
          {module.items?.map((item, index) => (
            <div
              className={`${index === activeIndex ? styles.active : ''} ${
                styles.carouselItem || ''
              }`}
              onClick={() => setActiveIndex(index)}
              key={keygen()}
            >
              <Slide
                slideTitle={`${module?.title}-carousel-${index + 1}`}
                item={item}
                gtmClass={gtmClass}
              />
            </div>
          ))}
        </div>
      </ScrollX>
    </div>
  );
};

Carousel.propTypes = {
  page: PropTypes.shape({
    title: PropTypes.string,
  }),
  module: PropTypes.shape({
    items: PropTypes.arrayOf(
      PropTypes.shape({
        title: PropTypes.string,
        content: PropTypes.string,
        primary_action: PropTypes.string,
        secondary_action: PropTypes.string,
      })
    ),
    name: PropTypes.string,
  }),
  gtmClass: PropTypes.string,
};

export default Carousel;
