import React from 'react'
import styled from 'styled-components'

import { LinearProgress as MuiProgressBar, linearProgressClasses, Typography } from '@mui/material'
import { ProgressBarBaseProps, CustomColor } from '../interfaces'

const ProgressBarStyled = styled(MuiProgressBar)<{ colorCustom?: CustomColor; $h?: number }>(
  ({ colorCustom, $h }) => ({
    width: '100%',
    height: $h ? `${$h}px` : '10px',
    borderRadius: '10px',
    position: 'relative',
    backgroundColor: colorCustom ? colorCustom.root : undefined,
    [`&.${linearProgressClasses.determinate}`]: {
      backgroundColor: colorCustom ? colorCustom.root : undefined,
    },
    [`& .${linearProgressClasses.bar}`]: {
      backgroundColor: colorCustom ? colorCustom.bar : undefined,
    },
  }),
)

const ProgressBarLabelStyled = styled(Typography)<{ $fSize?: string }>`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  position: relative;
  text-align: left;
  font-size: ${({ $fSize }) => $fSize || '1rem'};
`

export const ProgressBar = ({
  value = 0,
  label,
  variant = 'determinate',
  total,
  className,
  localeString,
  colorCustom,
  color = 'primary',
  htmlLabel,
  ...props
}: ProgressBarBaseProps) => {
  const percentage = value && total ? (value / total) * 100 : 0

  return (
    <div className={className} style={{ minWidth: '100px' }}>
      {label ? (
        <ProgressBarLabelStyled $fSize={props.fSize} className="ProgressBarLabel">
          {label}
          {!props.hideValue && (
            <span style={{ right: 0 }}>
              {localeString ? value.toLocaleString() : value} ({percentage.toFixed(2)}%)
            </span>
          )}
        </ProgressBarLabelStyled>
      ) : (
        htmlLabel
      )}

      <ProgressBarStyled
        value={percentage}
        variant={variant}
        colorCustom={colorCustom}
        $h={props.h}
        color={colorCustom ? undefined : color}
        {...props}
      />
    </div>
  )
}
