import {useMemo} from 'react';
import {View} from 'react-native';
import {Typography} from '@components/_core';
import {Spinner} from '@components/_HuGo';

import {styles} from './styles';

export interface PdfLoadingIndicatorProps {
  progress: number;
}

const MIN_PROGRESS = 0;
const MAX_PROGRESS = 100;

const getProgressPercentage = (progress: number): number => {
  if (!Number.isFinite(progress)) {
    return MIN_PROGRESS;
  }

  const normalizedProgress = progress <= 1 ? progress * MAX_PROGRESS : progress;

  return Math.min(
    MAX_PROGRESS,
    Math.max(MIN_PROGRESS, Math.round(normalizedProgress)),
  );
};

export function PdfLoadingIndicator({progress}: PdfLoadingIndicatorProps) {
  const progressPercentage = useMemo(
    () => getProgressPercentage(progress),
    [progress],
  );

  return (
    <View style={styles.container}>
      <Spinner />
      <Typography weight="semiBold">{`${progressPercentage}%`}</Typography>
    </View>
  );
}
