import React, { useCallback, useState } from 'react';
import { ColorName } from '@emotion/react';
import { Container, StyleSystemThemedProps } from 'components/layout';

export const VolumeLineGraph: React.FC<VolumeLineGraphType> = ({
  width,
  lineWidth = 5,
  activeLineColor,
  activeLinesCount = 0,
  lineBorderRadius = 0,
  lineColor = 'caption',
  ...props
}) => {
  const [parentWidth, setParentWidth] = useState(0);
  const lineCounts = Math.ceil(parentWidth / (lineWidth * 2));

  const marginLeft = useCallback(
    (index) => {
      return index > 0 ? lineWidth : 0;
    },
    [lineWidth]
  );
  const getBackgroundColor = useCallback(
    (index) => {
      return activeLinesCount < index + 1 ? lineColor : activeLineColor || 'primary';
    },
    [activeLineColor, activeLinesCount, lineColor]
  );
  return (
    <Container
      flexDirection="row"
      backgroundColor="transparent"
      width={width}
      height={25}
      onLayout={(event) => {
        const { width: layoutWidth } = event.nativeEvent.layout;
        setParentWidth(layoutWidth);
      }}
      {...props}
    >
      {Array(lineCounts)
        .fill(0)
        .map((_, index) => {
          return (
            <Container
              key={index}
              flexGrow={1}
              marginLeft={marginLeft(index)}
              width={lineWidth}
              borderRadius={lineBorderRadius}
              backgroundColor={getBackgroundColor(index)}
            />
          );
        })}
    </Container>
  );
};

type VolumeLineGraphType = StyleSystemThemedProps & VolumeLineGraphProps;

export interface VolumeLineGraphProps {
  lineColor?: ColorName;
  lineWidth?: number;
  activeLineColor?: ColorName;
  activeLinesCount?: number;
  lineBorderRadius?: number;
}
