// @flow
import React from 'react';
import styled from 'styled-components';

import { Box } from '../../../primitives/box';
import { getPaletteColor } from '../../../mixins/branding';

import type { TooltipViewProps } from './tooltip.proptypes';
import {
  getTooltipShadowColor,
  getCardBorderRadius,
} from './tooltip.css-rules';

// We need to set data-attribute to decide styling
// instead of using props so that Popper.JS can
// update positioning correctly.
const PopperBox = styled(Box)`
  background-color: ${getPaletteColor('white')};
  box-shadow: 0 5px 15px 0 ${getTooltipShadowColor};
  ${(props) => props.popperStyle};
  padding: 20px;
  border-radius: ${getCardBorderRadius};
  z-index: 30;
  max-width: 240px;
  &[data-placement*='bottom'] {
    margin-top: 15px;
  }
  &[data-placement*='top'] {
    margin-bottom: 15px;
  }
  &[data-placement*='right'] {
    margin-left: 15px;
  }
  &[data-placement*='left'] {
    margin-right: 15px;
  }
`;

const Arrow = styled.div`
  position: absolute;
  width: 20px;
  height: 20px;
  &[data-placement*='bottom'] {
    top: 0;
    left: 0;
    margin-top: -10px;
    &::before {
      border-width: 0 10px 10px 10px;
      border-color: transparent transparent ${getPaletteColor('white')}
        transparent;
    }
  }
  &[data-placement*='top'] {
    bottom: 0;
    left: 0;
    margin-bottom: -10px;
    filter: drop-shadow(0px 4px 2px ${getTooltipShadowColor});
    width: 20px;
    height: 10px;
    &::before {
      border-width: 10px 10px 0 10px;
      border-color: ${getPaletteColor('white')} transparent transparent
        transparent;
    }
  }
  &[data-placement*='right'] {
    left: 0;
    margin-left: -15px;
    filter: drop-shadow(-4px 0px 2px ${getTooltipShadowColor});
    &::before {
      border-width: 10px 10px 10px 0;
      border-color: transparent ${getPaletteColor('white')} transparent
        transparent;
    }
  }
  &[data-placement*='left'] {
    right: 0;
    margin-right: -15px;
    filter: drop-shadow(4px 0px 2px ${getTooltipShadowColor});
    &::before {
      border-width: 10px 0 10px 10px;
      border-color: transparent transparent transparent
        ${getPaletteColor('white')};
    }
  }
  &::before {
    content: '';
    margin: auto;
    display: block;
    width: 0;
    height: 0;
    border-style: solid;
  }
`;

export const TooltipView = React.forwardRef<*, *>(
  (
    { style, placement, arrowProps, popperId, children }: TooltipViewProps,
    ref,
  ) => (
    <PopperBox
      data-placement={placement}
      ref={ref}
      style={style}
      role="tooltip"
      id={popperId}
    >
      {children}
      <Arrow
        ref={arrowProps.ref}
        data-placement={placement}
        // $FlowFixMe workaround mismatch in CSS types.
        style={(arrowProps.style: any)}
      />
    </PopperBox>
  ),
);
