import React, {memo, useEffect, useRef} from 'react';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {useNavigation} from '@react-navigation/native';

import {useStepper} from '../../hooks/useStepper';
import {Step, StepperNavigationProp} from '../../interfaces';

const Stack = createNativeStackNavigator();

interface ScreenStackProps {
  children?: React.ReactNode;
}

interface StepScreenProps {
  Component: React.ComponentType;
}

const StepScreen = ({Component, ...props}: StepScreenProps) => {
  const navigation = useNavigation<StepperNavigationProp>();
  const {currentIndex, steps} = useStepper();
  const prevIndexRef = useRef(currentIndex);

  useEffect(() => {
    if (prevIndexRef.current !== currentIndex) {
      const targetStep = steps[currentIndex];
      if (targetStep?.id) {
        navigation.navigate(targetStep.id);
      }
      prevIndexRef.current = currentIndex;
    }
  }, [currentIndex, navigation, steps]);

  return <Component {...props} />;
};

const ScreenStack = ({children}: ScreenStackProps) => {
  const {steps} = useStepper();

  return (
    <Stack.Navigator
      screenOptions={{headerShown: false, gestureEnabled: false}}>
      {steps.map((step: Step, stepIndex: number) => (
        <Stack.Screen key={step.id} name={step.id} initialParams={{stepIndex}}>
          {screenProps => (
            <StepScreen
              Component={step.component as React.ComponentType}
              {...screenProps}
            />
          )}
        </Stack.Screen>
      ))}
      {children}
    </Stack.Navigator>
  );
};

const MemorizedScreenStack = memo(ScreenStack);
export {MemorizedScreenStack as ScreenStack};
