import { useRef } from 'react';
import { EnrichmentStatus } from './schema';

import { useTimer } from 'hooks/useTimer';

import { ProgressBar } from './ProgressBar';
import { getDuration } from 'utils/duration';

interface EnrichmentProgressProps extends EnrichmentStatus {
  style?: React.CSSProperties;
}

export const EnrichmentProgress: React.FC<EnrichmentProgressProps> = (
  props
) => {
  const estimate = props.estimatedTimeRemaining
    ? Math.round(props.estimatedTimeRemaining)
    : 0;
  const durationRef = useRef<HTMLSpanElement>(null);

  useTimer(
    (remainder) => {
      if (durationRef.current) {
        durationRef.current.textContent = remainder
          ? `(~${getDuration(remainder)})`
          : '';
      }
    },
    estimate * 1000,
    1000
  );

  const hasTasks = Boolean(props.tasksTotal);
  const progress = hasTasks
    ? (props.tasksCompleted / props.tasksTotal) * 100
    : 0;
  return (
    <ProgressBar
      progress={progress}
      animate={props.status === 'running'}
      className="pill bg-grayA02 paddingX3 fz12 tac truncate"
      style={{
        lineHeight: '24px',
      }}
      progressClassName="pill"
      progressStyle={{
        ...(props.status === 'failed' && {
          backgroundColor: 'hsla(340, 80%, 70%, 0.5)',
        }),
      }}
    >
      {props.status !== 'failed' ? (
        <div title={`Enriching... ${props.tasksCompleted}/${props.tasksTotal}`}>
          <span>Enriching...</span>
          <span> </span>
          {hasTasks && <span>{Math.round(progress)}%</span>}
          <span> </span>
          {estimate !== 0 && (
            <span ref={durationRef}>(~{getDuration(estimate * 1000)})</span>
          )}
        </div>
      ) : (
        <div>Failed</div>
      )}
    </ProgressBar>
  );
};
