import React from 'react'
import { isEmpty } from 'lodash'
import { connect } from 'react-redux'
import { Button } from '@pubsweet/ui'
import styled from 'styled-components'
import { th } from '@pubsweet/ui-toolkit'
import {
  compose,
  withState,
  lifecycle,
  withHandlers,
  setDisplayName,
} from 'recompose'

import {
  withModal,
  ConfirmationModal,
} from 'pubsweet-component-modal/src/components'

import { Err, Subtitle } from './FormItems'
import { parseSearchParams } from '../utils'
import {
  technicalDecision,
  technicalCheckFetcing,
} from '../../redux/technicalCheck'

const EQSDecisionPage = ({
  params,
  eqsDecision,
  errorMessage,
  successMessage,
}) => (
  <Root>
    <Title>
      Take a decision for manuscript <b>{params.customId}</b>.
    </Title>
    {errorMessage && <Err>{errorMessage}</Err>}
    {successMessage && <Subtitle>{successMessage}</Subtitle>}
    {isEmpty(errorMessage) &&
      isEmpty(successMessage) && (
        <ButtonContainer>
          <Button onClick={eqsDecision(false)}>REJECT</Button>
          <Button onClick={eqsDecision(true)} primary>
            ACCEPT
          </Button>
        </ButtonContainer>
      )}
  </Root>
)

export default compose(
  setDisplayName('EQS Decision page'),
  connect(
    state => ({
      isFetching: technicalCheckFetcing(state),
    }),
    { technicalDecision },
  ),
  withModal(({ isFetching }) => ({
    isFetching,
    modalComponent: ConfirmationModal,
  })),
  withState('params', 'setParams', {
    token: null,
    customId: null,
    collectionId: null,
  }),
  withState('successMessage', 'setSuccess', ''),
  withState('errorMessage', 'setError', ''),
  lifecycle({
    componentDidMount() {
      const { location, setParams } = this.props
      const { customId, collectionId, token } = parseSearchParams(
        location.search,
      )
      setParams({ customId, collectionId, token })
    },
  }),
  withHandlers({
    eqsDecision: ({
      setError,
      showModal,
      hideModal,
      setSuccess,
      technicalDecision,
      params: { collectionId, token },
    }) => decision => () => {
      showModal({
        title: `Are you sure you want to ${
          decision ? 'accept' : 'reject'
        } this EQS package?`,
        onConfirm: () => {
          technicalDecision({
            step: 'eqs',
            agree: decision,
            collectionId,
            token,
          })
            .then(() => {
              setSuccess(
                `Manuscript ${
                  decision ? 'accepted' : 'rejected'
                }. Thank you for your technical check!`,
              )
              hideModal()
            })
            .catch(() => {
              setError('There was an error. Please try again.')
              hideModal()
            })
        },
        onCancel: hideModal,
      })
    },
  }),
)(EQSDecisionPage)

// #region styles
const Root = styled.div`
  align-items: center;
  color: ${th('colorText')};
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin: 0 auto;
  text-align: center;
  width: 70vw;

  a {
    color: ${th('colorText')};
  }
`

const Title = styled.div`
  color: ${th('colorPrimary')};
  font-size: ${th('fontSizeHeading5')};
  font-family: ${th('fontHeading')};
  margin: 10px auto;
`

const ButtonContainer = styled.div`
  align-items: center;
  display: flex;
  justify-content: space-around;
  padding: calc(${th('gridUnit')} / 2);
  width: calc(${th('gridUnit')} * 15);
`
// #endregion