import { Box, LinearProgressBar, Text } from '@wix/design-system';
import { ImportState } from '@wix/bex-core';
import React, { useMemo } from 'react';
import { observer } from 'mobx-react-lite';

export interface ImportStepProgressProps {
  state: ImportState;
}

function _ImportStepProgress({ state }: ImportStepProgressProps) {
  const {
    processedCount,
    totalCount,
    isBackingUp,
    result,
    translate: t,
    importStatus,
    errorHandler,
  } = state;
  const progress =
    totalCount > 0
      ? Math.min(100, Math.round((processedCount / totalCount) * 100))
      : 0;

  const hasFailures = result != null && result.failed > 0;

  const errorMessage = useMemo(
    () =>
      importStatus.error
        ? errorHandler.getResolvedError?.(importStatus.error)?.message
        : null,
    [importStatus.error, errorHandler],
  );

  return (
    <Box direction="vertical" gap="SP2" width="100%">
      <LinearProgressBar
        value={progress}
        showProgressIndication
        dataHook="import-progress-bar"
      />
      <Text size="small" dataHook="import-progress-label">
        {isBackingUp && !errorMessage
          ? t('cairo.import.backupDescription')
          : t('cairo.import.progressLabel', {
              processed: processedCount,
              total: totalCount,
            })}
      </Text>
      {hasFailures && (
        <Text size="small" skin="error" dataHook="import-partial-error">
          {t('cairo.import.partialSuccess', {
            succeeded: result.succeeded,
            failed: result.failed,
          })}
        </Text>
      )}
      {errorMessage && (
        <Text size="small" skin="error" dataHook="import-error-message">
          {errorMessage}
        </Text>
      )}
    </Box>
  );
}

export const ImportStepProgress = observer(_ImportStepProgress);
