/*
 * Copyright (c) 2018-present, Revolut LTD.
 *
 * This source code is licensed under the Apache 2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */
/* eslint-disable react/no-typos */
import * as React from 'react'
import * as _ from 'lodash'
import { setAppElement } from 'react-modal'
import { css } from 'styled-components'
import withStyledClassNames from 'with-styled-class-names'
import { rgba as rgbaPolished } from 'polished'
import { ColorsFields } from '../../style/themeFields'
import { rgba } from '../../style/helpers'
import { colorGet, ifProp } from '../../style/utils'

const ReactModal = require('react-modal')

const getOverlayBackground = props => {
  const { isOpen } = props
  const defaultOverlayColor = colorGet(ColorsFields.BackgroundOverlay)(props) as string
  const colorOpened = _.get(
    props,
    'style.overlay.backgroundColor',
    rgbaPolished(defaultOverlayColor, 0.5),
  )
  const colorClosed = rgbaPolished(colorOpened, 0)
  return isOpen ? colorOpened : colorClosed
}
const isOpenOr = ifProp<ModalProps>('isOpen')
const contentStyle = css`
  @keyframes appear {
    0% {
      transform: scale(0.3);
      opacity: 0;
    }
    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

  position: relative;
  border: 1px solid ${colorGet(ColorsFields.Border)};
  background: ${colorGet(ColorsFields.BackgroundMain)};
  overflow: auto;
  border-radius: 4px;
  outline: none;
  padding: 4rem;
  min-width: 200px;
  min-height: 125px;
  transition: 0.3s all;
  opacity: ${isOpenOr(1, 0)};
  transform: ${isOpenOr('scale(1)', 'scale(0.3)')};
  animation: 0.3s ease-out 0s 1 appear;
`
const overlayStyle = css`
  @keyframes appearOverlay {
    0% {
      background-color: ${rgba(getOverlayBackground, 0)};
    }
    100% {
      background-color: ${getOverlayBackground};
    }
  }

  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: 0.3s all;
  background-color: ${getOverlayBackground};
  animation: 0.3s ease-out 0s 1 appearOverlay;
`
type ModalProps = {
  element: string
  closeTimeoutMS?: number
  isOpen?: boolean
  className?: string
}
export class Modal extends React.PureComponent<ModalProps, {}> {
  static StyledModal = withStyledClassNames(
    {
      className: contentStyle,
      overlayClassName: overlayStyle,
    },
    ReactModal,
  )
  static defaultProps = {
    closeTimeoutMS: 300,
    isOpen: false,
  }
  constructor(props) {
    super(props)
    // tslint:disable-next-line
    typeof window === 'object' && props.element && setAppElement(props.element)
  }
  render() {
    return <Modal.StyledModal {...this.props} overlayClassName={this.props.className} />
  }
}
