import React, { Fragment } from 'react'
import { get } from 'lodash'
import { Formik } from 'formik'
import styled from 'styled-components'
import { th } from '@pubsweet/ui-toolkit'
import { required } from 'xpub-validators'
import { compose, setDisplayName, withHandlers, withProps } from 'recompose'
import {
  H2,
  Button,
  Spinner,
  TextField,
  ValidatedFieldFormik,
} from '@pubsweet/ui'
import {
  Row,
  Item,
  Text,
  Label,
  IconButton,
  RowOverrideAlert,
  ItemOverrideAlert,
  ValidatedMenuField,
  withRoles,
  withFetching,
  withCountries,
} from 'pubsweet-component-faraday-ui'

// #region helpers
const setInitialRole = a => {
  if (get(a, 'admin', false)) {
    return 'admin'
  }
  if (get(a, 'handlingEditor', false)) {
    return 'handlingEditor'
  }
  if (get(a, 'editorInChief', false)) {
    return 'editorInChief'
  }
  return 'author'
}

const validate = values => {
  const errors = {}

  if (get(values, 'email', '') === '') {
    errors.email = 'Required'
  }

  return errors
}
// #endregion

const FormModal = ({
  edit,
  roles,
  title,
  titles,
  onClose,
  onSubmit,
  onConfirm,
  countries,
  isFetching,
  fetchingError,
  initialValues,
  confirmText = 'OK',
  cancelText = 'Cancel',
  user,
}) => (
  <Root>
    <IconButton icon="x" onClick={onClose} right={5} secondary top={5} />
    <H2>{title}</H2>
    {edit && (
      <Text mb={1} secondary>
        {get(user, 'email', '')}
      </Text>
    )}
    <Formik
      initialValues={initialValues}
      onSubmit={onSubmit}
      validate={validate}
    >
      {({ handleSubmit, ...rest }) => (
        <Fragment>
          {!edit && (
            <Row alignItems="baseline" mb={1} mt={1}>
              <ItemOverrideAlert mr={1} vertical>
                <Label required>Email</Label>
                <ValidatedFieldFormik
                  component={TextField}
                  inline
                  name="email"
                  validate={[required]}
                />
              </ItemOverrideAlert>
              <ItemOverrideAlert ml={1} vertical>
                <Label required>Role</Label>
                <ValidatedMenuField name="role" options={roles} />
              </ItemOverrideAlert>
            </Row>
          )}

          <Row mb={2}>
            <Item mr={1} vertical>
              <Label>First Name</Label>
              <ValidatedFieldFormik
                component={TextField}
                inline
                name="firstName"
              />
            </Item>
            <Item ml={1} vertical>
              <Label>Last Name</Label>
              <ValidatedFieldFormik
                component={TextField}
                inline
                name="lastName"
              />
            </Item>
          </Row>

          <RowOverrideAlert alignItems="center" mb={2}>
            <ItemOverrideAlert mr={1} vertical>
              <Label>Title</Label>
              <ValidatedMenuField name="title" options={titles} />
            </ItemOverrideAlert>
            <ItemOverrideAlert ml={1} vertical>
              <Label>Country</Label>
              <ValidatedMenuField name="country" options={countries} />
            </ItemOverrideAlert>
          </RowOverrideAlert>

          <Row mb={3}>
            {edit && (
              <ItemOverrideAlert mr={1} vertical>
                <Label required>Role</Label>
                <ValidatedMenuField name="role" options={roles} />
              </ItemOverrideAlert>
            )}
            <Item ml={edit && 1} vertical>
              <Label>Affiliation</Label>
              <ValidatedFieldFormik
                component={TextField}
                inline
                name="affiliation"
              />
            </Item>
          </Row>

          {fetchingError && (
            <Row mb={1}>
              <Text error>{fetchingError}</Text>
            </Row>
          )}

          {isFetching ? (
            <Spinner />
          ) : (
            <Row>
              <Button onClick={onClose}>Cancel</Button>
              <Button onClick={handleSubmit} primary>
                {confirmText}
              </Button>
            </Row>
          )}
        </Fragment>
      )}
    </Formik>
  </Root>
)

export default compose(
  withRoles,
  withFetching,
  withCountries,
  withProps(({ user, edit }) => ({
    initialValues: {
      ...user,
      role: setInitialRole(user),
    },
    confirmText: edit ? 'EDIT USER' : 'SAVE USER',
    title: edit ? 'Edit User' : 'Add User',
  })),
  withHandlers({
    onSubmit: ({ onSubmit, ...props }) => (values, formProps) => {
      if (typeof onSubmit === 'function') {
        onSubmit(values, { ...formProps, ...props })
      }
    },
    onClose: ({ onCancel, ...props }) => () => {
      if (typeof onCancel === 'function') {
        onCancel(props)
      }
      props.hideModal()
    },
  }),

  setDisplayName('AdminUserForm'),
)(FormModal)

// #region styles
const Root = styled.div`
  align-items: center;
  background: ${th('colorBackgroundHue')};
  border: ${th('borderWidth')} ${th('borderStyle')} transparent;
  border-radius: ${th('borderRadius')};
  box-shadow: ${th('boxShadow')};
  display: flex;
  flex-direction: column;
  position: relative;
  padding: calc(${th('gridUnit')} * 3);
  width: calc(${th('gridUnit')} * 60);

  ${H2} {
    margin: 0;
    text-align: center;
  }
`
// #endregion