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;
}

// A failed import's message is consumer-supplied and can be a single unbroken
// token — e.g. the server's `MISSING_REQUIRED_FIELDS` error joins every missing
// field with commas and no spaces (`handle,name,visible,…`), or a long URL/id.
// Without a break opportunity the browser treats it as one long word that
// overflows the fixed-width modal and gets clipped. Force it to wrap regardless
// of content (both properties are inherited, so they reach the `Text` inside).
const WRAP_LONG_WORDS: React.CSSProperties = {
  overflowWrap: 'break-word',
  wordBreak: 'break-word',
};

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

  const errorMessage = useMemo(
    () =>
      importStatus.isError
        ? errorHandler.getResolvedError?.(importStatus.error)?.message ??
          t('cairo.import.genericError')
        : null,
    [importStatus.isError, importStatus.error, errorHandler, t],
  );

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

export const ImportStepProgress = observer(_ImportStepProgress);
