import React, { Fragment } from 'react'
import { get } from 'lodash'
import { withProps } from 'recompose'
import styled from 'styled-components'
import { th } from '@pubsweet/ui-toolkit'
import { DateParser } from '@pubsweet/ui'

import { Label, Item, Row, Text, FileItem } from './'

const submittingAuthor = authors => {
  const thisAuthor = authors.filter(e => e.isSubmitting)
  return thisAuthor[0]
}

const AuthorReply = ({
  authorName,
  submittedOn,
  replyContent,
  replyFile,
  onDownload,
  onPreview,
}) => (
  <Root>
    <Row justify="space-between" mb={2}>
      <Item justify="flex-end">
        <Row mb={1}>
          <Item vertical>
            <Label mb={1 / 2}>Author Reply</Label>
            <Text whiteSpace="pre-wrap">{replyContent}</Text>
          </Item>
        </Row>
        <Text ml={1} mr={1} whiteSpace="nowrap">
          {authorName}
        </Text>
        <DateParser timestamp={submittedOn}>
          {date => <Text>{date}</Text>}
        </DateParser>
      </Item>
    </Row>

    {replyFile && (
      <Fragment>
        <Label mb={1 / 2}>File</Label>
        <Row justify="flex-start" mb={2}>
          <Item flex={0} mr={1}>
            <FileItem
              item={replyFile}
              onDownload={onDownload}
              onPreview={onPreview}
            />
          </Item>
        </Row>
      </Fragment>
    )}
  </Root>
)

export default withProps(
  ({ fragment: { authors, submitted }, authorReply }) => ({
    submittedOn: submitted,
    authorName: `${get(submittingAuthor(authors), 'firstName', '')} ${get(
      submittingAuthor(authors),
      'lastName',
      '',
    )}`,
    replyContent: get(authorReply, 'content', ''),
    replyFile: get(authorReply, 'file', ''),
  }),
)(AuthorReply)

// #region styles
const Root = styled.div`
  background-color: ${th('colorBackgroundHue')};
  border: ${th('borderWidth')} ${th('borderStyle')} ${th('colorBackgroundHue3')};
  border-radius: ${th('borderRadius')};
  padding: calc(${th('gridUnit')} * 2);
  margin: ${th('gridUnit')};
`
// #endregion