/** @jsx jsx */
import { useEffect, useMemo, useState } from 'react';
import { css, jsx } from '@emotion/react';
import debounce from 'lodash/debounce';
import { CustomThemeButton } from '@atlaskit/button';
import { akEditorUnitZIndex } from '@atlaskit/editor-shared-styles';
import CommentIcon from '@atlaskit/icon/glyph/comment';
import { layers } from '@atlaskit/theme/constants';
import Tooltip from '@atlaskit/tooltip';
import { commentMessages as messages } from '../media';
const commentBadgeWrapper = css({
  position: 'absolute',
  // closest parent element with position relative is .resizer-hover-zone, which includes 10px padding
  right: '2px',
  top: '2px',
  borderRadius: '3px',
  zIndex: akEditorUnitZIndex * 10
});
const commentBadgeEditorOverrides = css({
  right: '14px',
  zIndex: layers.card()
});
const getBadgeSize = (width, height) => {
  // width is the original width of image, not resized or currently rendered to user. Defaulting to medium for now
  return width && width < 70 || height && height < 70 ? 'small' : 'medium';
};
export const CommentBadge = ({
  intl,
  width,
  height,
  status = 'default',
  mediaElement,
  onClick,
  onMouseEnter,
  onMouseLeave,
  isEditor = false
}) => {
  const [badgeSize, setBadgeSize] = useState(getBadgeSize(width, height));
  const title = intl.formatMessage(messages.viewCommentsOnMedia);
  useEffect(() => {
    const observer = new ResizeObserver(debounce(entries => {
      const [entry] = entries;
      const {
        width,
        height
      } = entry.contentRect;
      setBadgeSize(getBadgeSize(width, height));
    }));
    if (mediaElement) {
      observer.observe(mediaElement);
    }
    return () => {
      observer.disconnect();
    };
  }, [mediaElement]);
  const badgeDimensions = badgeSize === 'medium' ? '24px' : '16px';
  const colourToken = useMemo(() => {
    switch (status) {
      case 'active':
        return "var(--ds-background-accent-yellow-subtlest-pressed, #F5CD47)";
      case 'entered':
        return "var(--ds-background-accent-yellow-subtlest-hovered, #F8E6A0)";
      default:
        return "var(--ds-background-accent-yellow-subtlest, #FFF7D6)";
    }
  }, [status]);
  return jsx("div", {
    css: isEditor ? [commentBadgeWrapper, commentBadgeEditorOverrides] : commentBadgeWrapper
    // This is needed so that mediaWrapperStyle in editor/editor-common/src/ui/MediaSingle/styled.tsx
    // can target the correct div
    ,
    "data-comment-badge": "true"
  }, jsx(Tooltip, {
    position: "top",
    content: title
  }, jsx(CustomThemeButton, {
    style: {
      height: badgeDimensions,
      width: badgeDimensions,
      background: colourToken,
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center'
    },
    onClick: onClick,
    onMouseEnter: onMouseEnter,
    onMouseLeave: onMouseLeave,
    iconAfter: jsx(CommentIcon, {
      label: title,
      size: badgeSize
    })
  })));
};