import React, {memo, useCallback} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {Button, Typography} from '@components';
import {useTheme} from '@shared/theme';

import {useStepper} from '../../hooks/useStepper';
import {FooterProps} from '../../interfaces';
import {styles} from './styles';

function Footer(initialProps: FooterProps) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const {footerProps, goNext, setData, goBack, currentIndex, steps} =
    useStepper();

  // Props are sum of initial + current step props
  const props = {...initialProps, ...footerProps};
  const {
    stepData,
    nextLabel,
    disabled,
    isLoading,
    showBackButton,
    backLabel,
    showContinueButton: continueEnabled,
    hidden,
    label,
    containerStyle,
  } = props;

  const onContinuePress = useCallback(() => {
    if (stepData) {
      setData(prev => ({...prev, [steps[currentIndex].id]: stepData}));
    }
    (props.goNext ?? goNext)?.();
  }, [stepData, props.goNext, goNext, setData, steps, currentIndex]);

  const onBackPress = useCallback(
    () => (footerProps.goBack ?? goBack)?.(),
    [footerProps.goBack, goBack],
  );

  if (hidden) {
    return null;
  }

  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: theme.background.layout.tertiary,
          shadowColor: theme.background.layout.inverted,
        },
        containerStyle,
      ]}>
      {continueEnabled && (
        <Button
          text={nextLabel ?? t('general.continue')}
          onPress={onContinuePress}
          disabled={disabled}
          isLoading={isLoading}
        />
      )}
      {showBackButton && (
        <Button
          variant="tertiary"
          text={backLabel ?? t('general.back')}
          onPress={onBackPress}
        />
      )}
      {label && (
        <Typography
          variant="xxs"
          color={theme.text.neutral.lighter}
          style={styles.label}>
          {label}
        </Typography>
      )}
    </View>
  );
}

const MemorizedFooter = memo(Footer);
export {MemorizedFooter as Footer};
