import React, {memo, useEffect} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import Text from '@components/Text';
import Button from '@components/Button';
import {useBackHandler} from '@hooks/useBackHandler';

import {styles} from './styles';

interface Props {
  totalSteps: number;
  currentstep: number;
  onBackPress: () => void;
  onNextPress: () => void;
  onSubmitPress: () => void;
  submitText: string;
  disableNext?: boolean;
  nextText?: string;
  backText?: string;
  forceEnableBack?: boolean;
  nextLoading?: boolean;
}

// TODO Guido: Change onPress logic to avoid receiving the onPress event as param
function FormFooter({
  totalSteps,
  currentstep,
  onBackPress,
  onSubmitPress,
  onNextPress,
  submitText,
  disableNext,
  forceEnableBack,
  nextLoading,
  nextText = 'general.next',
  backText = 'general.back',
}: Props) {
  const {t} = useTranslation();
  const isLastStep = currentstep === totalSteps;
  const progress = (currentstep / totalSteps) * 100;
  const isFirstStep = currentstep === 1;
  const animatedProgress = useSharedValue(0);

  useBackHandler(() => {
    onBackPress();
    return true;
  }, !isFirstStep);

  useEffect(() => {
    animatedProgress.value = withTiming(progress, {
      duration: 250,
    });
  }, [animatedProgress, progress]);

  const progressStyle = useAnimatedStyle(() => {
    return {
      width: `${animatedProgress.value}%`,
    };
  });

  return (
    <View>
      <View style={styles.progressLine} />
      <Animated.View style={[styles.progressLineDone, progressStyle]} />
      <View style={styles.container}>
        <View style={styles.leftContent}>
          <Button
            variant="text"
            onPress={onBackPress}
            disabled={isFirstStep && !forceEnableBack}
            leftIconName="arrowBack"
            text={t(backText)}
          />
        </View>
        <Text
          variant="subtitle1"
          align="center"
          style={styles.flex}>{`${currentstep}/${totalSteps}`}</Text>
        <View style={styles.flex}>
          <Button
            text={isLastStep ? submitText : t(nextText)}
            onPress={isLastStep ? onSubmitPress : onNextPress}
            disabled={disableNext || nextLoading}
            loading={nextLoading}
          />
        </View>
      </View>
    </View>
  );
}

export default memo(FormFooter);
