import React, { useState } from 'react';
import { getProgressBarColor, SUB_PROGRESS_COLOR } from './progressBar';
import { Label } from 'app/shared/components/text/text';
import { SvgWrapper } from 'app/shared/modules/chart/core';
import Measure from 'react-measure';
import cx from 'classnames';

export interface Props {
  labels: string[];
  additionalLabel?: string;
}

const dotSize = {
  height: 8,
  width: 8,
};

export const ProgressBarLegend = ({ labels, additionalLabel }: Props) => {
  const [ maxWidth, setMaxWidth ] = useState(0);
  const [ containerWidth, setContainerWidth ] = useState(0);
  const onResize = (contentRect) => {
    if (contentRect.bounds.width > maxWidth) {
      setMaxWidth(contentRect.bounds.width);
    }
  };
  const onContainerResize = (contentRect) => {
    setContainerWidth(contentRect.bounds.width);
  };

  return <Measure
    bounds
    onResize={onContainerResize}
  >
    {
      (props) => {
        const allLabels = additionalLabel ? [ ...labels, additionalLabel ] : labels;

        return <div className="o-layout o-layout--wrap" ref={props.measureRef}>
          {allLabels.map((label, index) => (
            <Measure
              key={`legend-${index}`}
              bounds
              onResize={onResize}
            >
              {
                (props) => {
                  const isAdditionalLabel = index === allLabels.length - 1 && additionalLabel;
                  const className = cx('o-layout', 'o-layout--aligned', 'u-margin-bottom', 'u-margin-right--medium', {
                    'u-animate-fade-in--fast': isAdditionalLabel,
                  });
                  return <div
                    className={className}
                    ref={props.measureRef}
                    style={maxWidth * allLabels.length > containerWidth ? { minWidth: maxWidth } : {}}
                  >
                    {/*@ts-ignore*/}
                    <SvgWrapper
                      height={dotSize.height + 1}
                      width={dotSize.width}
                      margin={{ top: 0, left: 0 }}
                    >
                      <rect
                        width={dotSize.width}
                        height={dotSize.height}
                        rx={dotSize.height / 2}
                        fill={isAdditionalLabel ? SUB_PROGRESS_COLOR : getProgressBarColor(index)}
                      />
                    </SvgWrapper>
                    <Label extraClass="u-no-wrap u-margin-bottom--tiny u-margin-left">{label}</Label>
                  </div>;
                }
              }
            </Measure>
          ))}
        </div>;
      }
    }
  </Measure>;
};
