import React from 'react';
import { StyleSheet } from 'react-native';
import { TabScreen } from './StyledScrollableTabs';

const SceneView = ({
  lazy = false,
  lazyPreloadDistance = 1,
  children,
  index,
  selectedIndex,
  testID,
}: {
  children: React.ReactNode;
  index: number;
  selectedIndex: number;
  lazy?: boolean;
  lazyPreloadDistance?: number;
  testID?: string;
}) => {
  const [isLoading, setIsLoading] = React.useState(
    Math.abs(selectedIndex - index) > lazyPreloadDistance
  );
  const focused = index === selectedIndex;

  React.useEffect(() => {
    if (isLoading && Math.abs(selectedIndex - index) <= lazyPreloadDistance) {
      // Always render the route when it becomes focused
      setIsLoading(false);
    }
  }, [isLoading, index, selectedIndex, lazyPreloadDistance]);

  React.useEffect(() => {
    let unsubscribe: (() => void) | undefined;
    let timer: ReturnType<typeof setTimeout>;

    if (!lazy && isLoading) {
      // If lazy mode is not enabled, render the scene with a delay if not loaded already
      // This improves the initial startup time as the scene is no longer blocking
      timer = setTimeout(() => setIsLoading(false), 0);
    }

    return () => {
      unsubscribe?.();

      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [index, isLoading, lazy, focused]);

  return (
    <TabScreen
      accessibilityElementsHidden={!focused}
      importantForAccessibility={focused ? 'auto' : 'no-hide-descendants'}
      style={[
        { flex: 1, overflow: 'hidden' },
        focused ? StyleSheet.absoluteFill : null,
      ]}
      testID={testID}
    >
      {focused || !isLoading ? children : null}
    </TabScreen>
  );
};

export default SceneView;
