import React, {useCallback, useState} from 'react';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useTheme} from '@shared/theme';

import {StepSelector} from './components/StepSelector';
import {Header} from './components/Header';
import {FooterProps, HeaderProps, Step, StepperProps} from './interfaces';
import {styles} from './styles';
import {Footer} from './components/Footer';
import {Data, StepperContext} from './context/StepperContext';
import {Content} from './components/Content';
import {ScreenStack} from './components/ScreenStack';
import {StepperProgressBar} from './components/ProgressBar';

/*
 * Make sure the screens rendered are using React.memo
 * */
export function Stepper<TSteps extends readonly Step[] = Step[]>({
  steps,
  title,
  onClose,
  defaultIndex = 0,
  children,
  containerStyle,
  hideClose,
}: StepperProps) {
  const [index, setIndex] = useState<number>(defaultIndex);
  const {theme} = useTheme();
  const [isVisibleStepsModal, setIsVisibleModal] = useState(false);
  const [data, setData] = useState<Data<TSteps>>({});

  const goToStep = useCallback((stepIndex: number) => {
    setIndex(stepIndex);
  }, []);

  const goBack = useCallback(() => {
    if (!index) {
      onClose();
      return;
    }
    setIndex(prev => prev - 1);
  }, [index, onClose]);

  const goNext = useCallback(() => {
    setIndex(prev => prev + 1);
  }, []);

  const [headerProps, setHeaderProps] = useState<HeaderProps>({
    onClose,
    title,
    hideClose,
  });

  const [footerProps, setFooterProps] = useState<FooterProps>({
    showContinueButton: true,
  });

  return (
    <StepperContext.Provider
      value={{
        currentIndex: index,
        goNext,
        goBack,
        goToStep,
        setFooterProps,
        footerProps,
        setHeaderProps,
        headerProps,
        data,
        setData,
        steps,
        totalStepsCount: steps.length,
        setIsVisibleModal,
        isVisibleStepsModal,
        onClose,
      }}>
      <SafeAreaView
        style={[
          styles.flex,
          {
            backgroundColor: footerProps.hidden
              ? theme.background.layout.default
              : theme.background.layout.tertiary,
          },
          containerStyle,
        ]}>
        {children}
      </SafeAreaView>
    </StepperContext.Provider>
  );
}

Stepper.Header = Header;
Stepper.Footer = Footer;
Stepper.StepSelector = StepSelector;
Stepper.ProgressBar = StepperProgressBar;
Stepper.Content = Content;
Stepper.ScreenStack = ScreenStack;

export * from './hooks/useStepper';
export * from './interfaces';
