import { useRef } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import IfActive from "../../application/IfActive/index.js";
import getColor from "../../../utils/colors/getColor.js";
import useZoomContext from '../hooks/useZoomContext';
import LeaderLine from './LeaderLine';
import styles from './styles.module.scss';
const Label = function Label(props) {
  const {
    label,
    center,
    labelOffset,
    labelLimits,
    className,
    leaderLineClassName,
    ...restProps
  } = props;
  const ref = useRef();
  const {
    transform,
    canvas
  } = useZoomContext();
  const labelScale = `scale(${1 / canvas.svgToPixelScale}) scale(${1 / transform.k})`;
  const {
    zoomLevel
  } = transform;
  const [cx, cy] = center;
  const [offsetX, offsetY] = labelOffset || [0, 0];
  const t = Math.min(1, zoomLevel * 2);
  const x = cx + offsetX * (1 - t);
  const y = cy + offsetY * (1 - t);
  const {
    after: limitAfter = 0,
    before: limitBefore = 1
  } = labelLimits || {};
  const {
    fill = getColor('warmgray-100'),
    stroke
  } = restProps;
  const textProps = labelOffset ? {
    fill: getColor('warmgray-100'),
    stroke: 'white'
  } : {
    fill,
    stroke
  };
  const outOfBounds = zoomLevel < limitAfter || zoomLevel > limitBefore;
  if (!label || outOfBounds) {
    return null;
  }
  return <g style={{
    transformOrigin: `${x}px ${y}px`
  }} transform={labelScale}>
      <text ref={ref} x={x} y={y} className={classnames(styles.label, className)} {...textProps}>
        {label}
      </text>
      <IfActive active={!!labelOffset && t < 0.5}>
        <LeaderLine id={label} start={[x, y]} end={[cx, cy]} clippingRef={ref} className={leaderLineClassName} />
      </IfActive>
    </g>;
};
Label.defaultProps = {
  label: undefined,
  labelOffset: undefined,
  labelLimits: undefined,
  className: undefined,
  leaderLineClassName: undefined
};
Label.propTypes = {
  label: PropTypes.string,
  center: PropTypes.arrayOf(PropTypes.number).isRequired,
  labelOffset: PropTypes.arrayOf(PropTypes.number),
  labelLimits: PropTypes.shape({
    after: PropTypes.number,
    before: PropTypes.number
  }),
  className: PropTypes.string,
  leaderLineClassName: PropTypes.string
};
export default Label;