import {useCallback, useEffect, useMemo} from 'react';
import {Animated} from 'react-native';

import {RenderSceneProps, TabItem, TabsHeaderProps} from '../interfaces';

interface Params {
  index: number;
  routes: TabItem[];
  onIndexChange: (indexValue: number) => void;
}

interface Result {
  sceneProps: RenderSceneProps;
  tabBarProps: TabsHeaderProps;
}

export const useTabsChipsPager = ({
  index,
  routes,
  onIndexChange,
}: Params): Result => {
  const layout = useMemo(() => ({width: 0, height: 0}), []);
  const position = useMemo(() => new Animated.Value(index), [index]);

  useEffect(() => {
    position.setValue(index);
  }, [index, position]);

  const jumpTo = useCallback(
    (key: string) => {
      const newIndex = routes.findIndex(route => route.key === key);
      if (newIndex !== -1) {
        onIndexChange(newIndex);
      }
    },
    [onIndexChange, routes],
  );

  const tabBarProps = useMemo(
    () => ({
      navigationState: {index, routes},
      jumpTo,
      position,
      layout,
    }),
    [index, jumpTo, layout, position, routes],
  );

  const currentRoute = routes[index] || routes[0];
  const sceneProps = useMemo(
    () => ({
      route: currentRoute,
      jumpTo,
      position,
      layout,
    }),
    [currentRoute, jumpTo, layout, position],
  );

  return {sceneProps, tabBarProps};
};
