import React, { useState } from "react";
import PropTypes from "prop-types";
import {
  Container,
  HandleValue,
  MaxValue,
  MinValue,
  ProgressBarAvailable,
  ProgressBarContainer,
  ProgressBarTotal,
  ProgressBarUsed,
  ProgressHandle,
} from "./styles";

const defaultSize = "md";

const ProgressBar = ({
  total,
  used,
  available,
  max,
  size,
  disabled,
  onAdjust,
}) => {
  const [handlePosition, setHandlePosition] = useState((used / max) * 100);

  const handleAdjust = (e) => {
    if (!disabled) {
      const containerWidth = e.currentTarget.offsetWidth;
      const newPosition = Math.min(
        100,
        Math.max(
          0,
          ((e.clientX - e.currentTarget.getBoundingClientRect().left) /
            containerWidth) *
            100
        )
      );
      setHandlePosition(newPosition);
      const newUsed = Math.floor((newPosition / 100) * max);
      onAdjust(newUsed);
    }
  };

  const usedWidth = (used / total) * 100;
  const availableWidth = (available / max) * 100;

  return (
    <Container disabled={disabled}>
      <ProgressBarContainer
        onClick={handleAdjust}
        disabled={disabled}
        size={size}
      >
        <ProgressBarTotal
          color="#FEBF10"
          width={100}
          left={0}
          disabled={disabled}
        />
        <ProgressBarUsed
          color="#30D568"
          width={usedWidth}
          left={0}
          disabled={disabled}
        />
        <ProgressBarAvailable
          color="#00C2C2"
          width={availableWidth}
          left={0}
          disabled={disabled}
        />
        <ProgressHandle left={handlePosition} disabled={disabled}>
          <HandleValue disabled={disabled}>{used}</HandleValue>
        </ProgressHandle>
        <MinValue disabled={disabled}>{0}</MinValue>
        <MaxValue disabled={disabled}>{max}</MaxValue>
      </ProgressBarContainer>
    </Container>
  );
};

ProgressBar.propTypes = {
  total: PropTypes.number,
  used: PropTypes.number,
  available: PropTypes.number,
  max: PropTypes.number,
  size: PropTypes.oneOf(["xs", "sm", "md", "lg", "xl"]),
  disabled: PropTypes.bool,
  onAdjust: PropTypes.func,
};

ProgressBar.defaultProps = {
  size: defaultSize,
  disabled: false,
};

export default ProgressBar;
