import React, { useReducer } from 'react';
import { useAnimatedListItems } from './useAnimatedListItems';

type Mutation = 'reverse' | 'randomize' | 'insert' | 'remove';

export const AnimatedListDemo = () => {
  const [items, mutateItems] = useReducer(
    (prevState: string[], mutation: Mutation) => {
      switch (mutation) {
        case 'reverse':
          const newState = [...prevState];
          newState.reverse();
          return newState;
        default:
          return prevState;
      }
    },
    ['Item 0', 'Item 1', 'Item 2', 'Item 3'],
  );

  const { updateItemRef, updateItemPositions, itemStyles } =
    useAnimatedListItems({ keys: items });

  return (
    <main>
      <ol>
        {items.map((item) => {
          return (
            <li
              key={item}
              ref={(li) => updateItemRef(item, li)}
              style={itemStyles[item]}
            >
              {item}
            </li>
          );
        })}
      </ol>
      <button
        type="button"
        onClick={() => {
          updateItemPositions();
          mutateItems('reverse');
        }}
      >
        Reverse
      </button>
    </main>
  );
};
