import React, { ReactElement, useState, useEffect } from 'react';
import css from '../../utils/css';
import ProgressBar, { ProgressBarProps } from './ProgressBar';
import ProgressCircle from './ProgressCircle';
import assert from '../../utils/assert';
import { CommonProps } from '../common';

export interface ProgressProps extends CommonProps {
  /**
   * Set intent for your custom progress.
   */
  intent?: 'primary' | 'success' | 'warning' | 'danger' | 'error';
  /**
   * Size of progress.
   */
  size?: 'small' | 'medium';
  /**
   * Status of progress. Use `custom` if you wanna control the intent of the progress on your own.
   */
  status?: 'active' | 'exception' | 'custom';
  /**
   * The progress completion percentage: 0-100.
   */
  value: number;
  /**
   * Progress type.
   */
  variant?: 'bar' | 'circle';
  /**
   * Whether to display the progress value and the status icon.
   */
  withInfo?: boolean;
}

const Progress = ({
  intent = 'primary',
  size = 'medium',
  withInfo = true,
  status = 'active',
  value,
  variant = 'bar',
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: ProgressProps): ReactElement => {
  assert(
    value >= 0 && value <= 100,
    `[Progress] value:${value} is not in range [0, 100]`
  );
  const [percentage, setPercentage] = useState<number>(value);
  const [internalIntent, setInternalIntent] = useState<
    ProgressBarProps['intent']
  >(intent);

  useEffect((): void => {
    setPercentage(value);

    switch (status) {
      case 'active':
        setInternalIntent(value === 100 ? 'success' : 'primary');
        break;
      case 'exception':
        setInternalIntent('danger');
        break;
      case 'custom':
        setInternalIntent(intent);
        break;
    }
  }, [value, status, intent]);

  return (
    <>
      {variant === 'bar' && (
        <ProgressBar
          intent={internalIntent}
          size={size}
          status={status}
          withInfo={withInfo}
          value={percentage}
          id={id}
          className={className}
          style={{ ...style, ...css(sx) }}
          data-test-id={dataTestId}
        />
      )}
      {variant === 'circle' && (
        <ProgressCircle
          intent={internalIntent}
          size={size}
          status={status}
          withInfo={withInfo}
          value={percentage}
          id={id}
          className={className}
          style={{ ...style, ...css(sx) }}
          data-test-id={dataTestId}
        />
      )}
    </>
  );
};

export default Progress;
