import React, { useEffect } from 'react';
import { Data } from '../../../types';

interface RowAnimationProps<T> {
  data: T;
}

export const useRowAnimation = <T extends Data>(): {
  AnimatedRow: React.FC<RowAnimationProps<T>>;
  setLastAddedItem: React.Dispatch<React.SetStateAction<T | undefined>>;
  setShouldAnimate: React.Dispatch<React.SetStateAction<boolean>>;
} => {
  const [lastAddedItem, setLastAddedItem] = React.useState<T | undefined>();
  const [shouldAnimate, setShouldAnimate] = React.useState<boolean>(false);

  useEffect(() => {
    if (shouldAnimate && lastRowRef.current) {
      lastRowRef.current.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
      });

      setShouldAnimate(false);
    }
  }, [shouldAnimate]);

  const lastRowRef = React.useRef<HTMLDivElement>(null);

  const AnimatedRow: React.FC<RowAnimationProps<T>> = ({ data, children }) => {
    return (
      <div ref={lastAddedItem === data ? lastRowRef : undefined}>
        {children}
      </div>
    );
  };

  return { AnimatedRow, setLastAddedItem, setShouldAnimate };
};
