import React from 'react';
import styled from 'styled-components';
import { uiFonts } from '../constants/uiFonts';

export interface IBarProps {
  max: number;
  value: number;
  color: 'red' | 'blue' | 'green';
  style?: Record<string, any>;
  displayText?: boolean;
  percentageWidth?: number;
  minWidth?: number;
  mobileScale?: number;
}

export const ProgressBar: React.FC<IBarProps> = ({
  max,
  value,
  color,
  displayText = true,
  percentageWidth = 40,
  minWidth = 100,
  style,
  mobileScale,
}) => {
  value = Math.round(value);
  max = Math.round(max);

  const calculatePercentageValue = function(max: number, value: number) {
    if (value > max) {
      value = max;
    }
    return (value * 100) / max;
  };

  return (
    <Container
      className="rpgui-progress"
      data-value={calculatePercentageValue(max, value) / 100}
      data-rpguitype="progress"
      percentageWidth={percentageWidth}
      minWidth={minWidth}
      style={style}
      mobileScale={mobileScale}
    >
      {displayText && (
        <TextOverlay>
          <ProgressBarText>
            {value}/{max}
          </ProgressBarText>
        </TextOverlay>
      )}
      <div className=" rpgui-progress-track">
        <div
          className={`rpgui-progress-fill ${color} `}
          style={{
            left: '0px',
            width: calculatePercentageValue(max, value) + '%',
          }}
        ></div>
      </div>
      <div className=" rpgui-progress-left-edge"></div>
      <div className=" rpgui-progress-right-edge"></div>
    </Container>
  );
};

const ProgressBarText = styled.span`
  font-size: ${uiFonts.size.small} !important;
  color: white;
  text-align: center;
  z-index: 1;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 12px;
`;

const TextOverlay = styled.div`
  width: 100%;
  position: relative;
`;

interface IContainerProps {
  percentageWidth?: number;
  minWidth?: number;
  style?: Record<string, any>;
  mobileScale?: number;
}

const Container = styled.div<IContainerProps>`
  display: flex;
  flex-direction: column;
  min-width: ${props => props.minWidth}px;
  width: ${props => props.percentageWidth}%;
  justify-content: start;
  align-items: flex-start;
  ${props => props.style}
  @media (max-width: 950px) {
    transform: scale(${props => props.mobileScale});
  }
`;
