import React from 'react'

import styles from './_progress-bar.module.scss'
import FormLabel from '../FormLabel/FormLabel'
import Icon from '../Icons/Icon'
import Spinner from '../Spinner/Spinner'
import { c } from '../../translations/LibraryTranslationService'

type ProgressBarBaseProps = {
  /** Current progress that should be shown. Range from 0 - 100 */
  percentage: number
  /** Optional text below the ProgressBar */
  helperText?: string
  /** Optionally style the ProgressBar as an error */
  error?: boolean
  /** Optional prop to add a test id to the ProgressBar for QA testing */
  qaTestId?: string
}

type FormLabelProps = React.ComponentProps<typeof FormLabel>

type ProgressBarWithLabel = ProgressBarBaseProps & {
  /** Optional label above the ProgressBar */
  formLabelProps?: Omit<FormLabelProps, 'rightLabel' | 'error'> & {
    showRightLabel?: boolean
  }
}

type ProgressBarWithoutLabel = ProgressBarBaseProps & {
  formLabelProps?: never
  showPercentageText?: never
}

export type ProgressBarProps = ProgressBarWithLabel | ProgressBarWithoutLabel

const ProgressBar = ({
  percentage = 0,
  formLabelProps,
  helperText,
  error,
  qaTestId = 'progress-bar',
}: ProgressBarProps): React.JSX.Element => {
  if (percentage < 0 || percentage > 100) {
    throw new Error(c('errorProgressBar'))
  }

  return (
    <div className={styles.progressBarContainer} qa-test-id={qaTestId}>
      {formLabelProps ? (
        <FormLabel
          {...formLabelProps}
          {...(formLabelProps.showRightLabel
            ? {
                rightLabel: (
                  <div className={styles.rightLabelContainer}>
                    {!error ? (
                      <span>
                        {percentage}
                        {c('percentageSymbol')}
                      </span>
                    ) : null}
                    {error ? (
                      <Icon icon='caution' color='dark-red' iconSize='12px' />
                    ) : percentage < 100 ? (
                      <Spinner />
                    ) : (
                      <Icon
                        icon='check'
                        className={styles.checkIcon}
                        iconSize='12px'
                      />
                    )}
                  </div>
                ),
              }
            : {})}
        />
      ) : null}
      <div className={styles.progressBottomBar}>
        <div
          className={styles.progressBottomBarActive}
          style={{
            width: `${percentage}%`,
            backgroundColor: error
              ? 'var(--dark-red)'
              : percentage < 100
                ? 'var(--dark-blue)'
                : 'var(--dark-green)',
          }}
        />
      </div>
      {helperText ? (
        <div className={`${styles.helperText} ${error ? styles.hasError : ''}`}>
          {helperText}
        </div>
      ) : null}
    </div>
  )
}

export default ProgressBar
