import React, { Children, useEffect, useRef, useState } from 'react';
import classes from './Carousel.module.css';

interface Props {
  children: React.ReactNode;
}

export default function Carousel({ children }: Props): JSX.Element {
  const [activeItem, setActiveItem] = useState(0);
  const content = useRef<HTMLDivElement>(null);
  const maxItems = Children.count(children) - 1;

  useEffect(() => {
    if (content.current == null) return;

    const offset = content.current.clientWidth * activeItem;
    // const offset = 100 * activeItem;
    //
    console.log(offset, activeItem, content.current.clientWidth);

    content.current.style.transform = `translate3d(-${offset}px, 0px, 0px)`;
  }, [activeItem]);

  const offsetActiveItem = (offset: number): void => {
    setActiveItem((prev) => {
      const newActiveItem = prev + offset;

      // Wrap on end in both sides
      if (newActiveItem < 0) {
        return maxItems;
      }

      if (newActiveItem > maxItems) {
        return 0;
      }

      return newActiveItem;
    });
  };

  return (
    <div className={classes.carousel}>
      <button
        className={classes.btnPrev}
        onClick={() => {
          offsetActiveItem(-1);
        }}
      >
        Prev
      </button>
      <div className={classes.container}>
        <div ref={content} className={classes.content}>
          {children}
        </div>
      </div>
      <button
        className={classes.btnNext}
        onClick={() => {
          offsetActiveItem(1);
        }}
      >
        Next
      </button>
    </div>
  );
}
