import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';

import v from '../../styles/Variables';

import UnderlineButton from '../Common/UnderlineButton';

interface Props {
  callback: () => void;
  focusCb?: () => void;
  blurCb?: () => void;
  content: React.ReactNode;
  id: string;
  position: string;
  showQuestion?: boolean;
  theme: string;
  themeTooltip: string;
  themeWrapper?: string;
  title: string;
  width: number;
  showOnHover?: boolean;
}

interface Styles {
  elementWidth: number;
  width: number;
  position: string;
  left: string;
}

// A manually activated tooltip
const Tooltip2 = ({
  callback,
  focusCb = () => null,
  blurCb = () => null,
  content,
  id = 'tooltip2',
  position,
  showQuestion = false,
  showOnHover = false,
  theme,
  themeTooltip,
  themeWrapper,
  title,
  width,
}: Props) => {
  const [show, showSetter] = useState(false);
  const [elementWidth, elementWidthSetter] = useState(0);
  const wrapperRef = useRef<HTMLDivElement>(null);

  let left = '0';
  if (position === 'left') {
    left = `-${width + 8}px`;
  } else if (position === 'right') {
    left = '105%';
  } else if (position === 'square') {
    left = '0';
  } else {
    left = `${elementWidth / 2 - width / 2}px`;
  }

  useEffect(() => {
    document.addEventListener('click', handleClickOutside, false);
    return () => {
      document.removeEventListener('click', handleClickOutside, false);
    };
  }, []);

  const handleClickOutside = (event: { target: any }) => {
    if (wrapperRef && wrapperRef.current && !wrapperRef.current.contains(event.target)) {
      showSetter(false);
    }
  };

  return (
    <Wrapper data-test="component-tooltip" id={id} className={`nwc--tooltip ${themeWrapper}`} ref={wrapperRef}>
      <Trigger
        className={theme}
        onBlur={(e) => {
          blurCb();
          elementWidthSetter(e.currentTarget.offsetWidth);
          // setTimeout(() => {
          //   showSetter(false);
          // }, 200);
        }}
        onFocus={(e) => {
          focusCb();
          elementWidthSetter(e.currentTarget.offsetWidth);
        }}
        onClick={() => {
          callback();
          showSetter(!show);
        }}
        onMouseEnter={() => {
          showOnHover && showSetter(true);
        }}
        onMouseLeave={() => {}}
        aria-expanded={show === true ? 'true' : 'false'}
        aria-controls={`tooltip--${title.replace(/\s/g, '')}`}
      >
        <UnderlineButton title={title} />{' '}
        {showQuestion === true ? (
          <sup>
            <i className="fas fa-question-circle" aria-label="click to see tooltip" />
          </sup>
        ) : (
          <span className="sr-only">{title}</span>
        )}
      </Trigger>
      <Background
        id={`tooltip--${title.replace(/\s/g, '')}`}
        className={show !== true ? 'opacity-0' : `${themeTooltip} nwc--tooltip-${position} opacity-1`}
        elementWidth={elementWidth}
        width={width}
        position={position}
        left={left}
        role="tooltip"
      >
        {content}
      </Background>
    </Wrapper>
  );
};

export default Tooltip2;

/* styles */
const Wrapper = styled.span`
  display: inline-block;
  position: relative;
  text-align: center;
`;

const Trigger = styled.button`
  background: none;
  border: none;
  padding: 0;
  cursor: help;
  &:focus {
    outline: 2px dotted black;
    outline-offset: 2px;
  }
`;

const Background = styled.div<Styles>`
  position: absolute;
  background: ${v.colors.dark222};
  color: ${v.colors.light};
  text-align: center;
  width: ${({ width }) => `${width}px`};
  z-index: 9999;
  font-size: 14px;
  padding: 8px;
  top: ${({ position }) => (position === 'top' ? null : null)};
  bottom: ${({ position }) => (position === 'top' ? '100%' : null)};
  left: ${({ left }) => left};
  margin-top: ${({ position }) => (position === 'left' || position === 'right' ? '-30%' : 0)};
`;
