// CreateUserForm Component
import React, { Fragment, PureComponent } from 'react';
import PropTypes from 'prop-types';
import { noop } from 'node-noop';
import { Field, FieldArray } from 'redux-form';

// Material Components
import Grid from '@material-ui/core/Grid';
import MenuItem from '@material-ui/core/MenuItem';
import { withStyles } from '@material-ui/core/styles';
import { Typography } from '@material-ui/core';
import Button from '@material-ui/core/Button';
import Switch from '@material-ui/core/Switch';
import AddIcon from '@material-ui/icons/Add';
import TextInput from '../TextInput/TextInput';

// Components
import Alert from '../Alert/Alert';
import RadioInput from '../RadioInput/RadioInput';
import MoreVertical from '../MoreVertical/MoreVertical';

import green from '../../../style/theme/colors/green';

const styles = theme => ({
  list: {
    listStyleType: 'none',
    paddingLeft: '0px'
  },
  addButton: {
    color: green[200],
    cursor: 'pointer'
  },
  addButtonText: {
    display: 'inline-block'
  },
  hr: {
    margin: `0px -${theme.spacing.unit * 2}px`,
    height: '3px',
    background: '#c2c2c2'
  },
  submitButton: {
    marginTop: theme.spacing.unit * 8,
    marginBottom: theme.spacing.unit * 8
  }
});

const categories = [{ name: 'Food', value: 'food' },
  { name: 'Medication', value: 'medication' },
  { name: 'Environment', value: 'environment' },
  { name: 'Biologic', value: 'biologic' }];

const renderAllergies = ({ fields, meta: { error, submitFailed }, classes }) => (
  <ul>
    {fields.map((allergy, index) => (
      <Fragment>
        <li className={classes.list} key={index}>
          <Grid
            container
            justify="space-between"
            alignItems="center"
          >
            <Grid
              item
              xs={9}
            >
              <Field
                name={`${allergy}.category`}
                select
                label="Category"
                fullWidth
                required
                component={TextInput}
              >
                {categories.map(option => (
                  <MenuItem key={option.name} value={option.value}>
                    {option.name}
                  </MenuItem>
                ))}
              </Field>
            </Grid>

            <MoreVertical
              fields={fields}
              menuItems={[{ text: 'delete', index }]}
            />

          </Grid>

          <Field
            name={`${allergy}.substance.codification`}
            type="text"
            label="Substance"
            required
            component={TextInput}
          />
          <Field
            name={`${allergy}.reaction.note`}
            type="text"
            label="Reaction"
            component={TextInput}
          />
          <RadioInput
            fieldName={`${allergy}.criticality`}
            fieldLabel="Risk"
            radioButtons={[{ label: 'Low', value: 'low' },
              { label: 'High', value: 'high' }]}
          />
        </li>
        <hr className={classes.hr} />
      </Fragment>
    ))}

    <li className={classes.list}>

      <Grid
        container
        justify="flex-start"
        alignItems="center"
        onClick={() => fields.push({})}
        className={classes.addButton}
      >
        <AddIcon />
        <Typography
          variant="subtitleSmallMedium"
          color="inherit"
          className={classes.addButtonText}
        >
        add another
        </Typography>
      </Grid>


      {submitFailed && error && (
      <span>
        {error}
      </span>
      )}
    </li>
  </ul>
);

class AddAllergiesForm extends PureComponent {
  state={
    haveAllergies: false
  }

  componentDidMount() {
    const { change, patient, recorder } = this.props;
    change('patient', patient);
    change('recorder', recorder);
  }

  handleChange = (payload) => {
    const { change } = this.props;
    this.setState(prevState => ({
      haveAllergies: !prevState.haveAllergies
    }), () => change('allergies', payload));
  }

  render() {
    const {
      messages, handleSubmit, error, classes
    } = this.props;

    const { haveAllergies } = this.state;

    return (
      <Fragment>
        <Grid
          container
          justify="space-between"
          alignItems="center"
        >
          <Typography
            variant="display1"
            color="inherit"
            className={classes.title}
          >
            {'Do you have any Allergies?'}
          </Typography>

          <Switch
            color="primary"
            checked={haveAllergies}
            onChange={haveAllergies ? () => this.handleChange([]) : () => this.handleChange([{}])}
          />
        </Grid>

        {error && <Alert messages={messages} type={error} />}

        <form onSubmit={handleSubmit}>
          {haveAllergies
            ? <FieldArray name="allergies" props={{ classes }} component={renderAllergies} />
            : null}
          <Button
            type="submit"
            color="primary"
            variant="contained"
            className={classes.submitButton}
          >
          SUBMIT
          </Button>
        </form>
      </Fragment>
    );
  }
}


AddAllergiesForm.propTypes = {
  handleSubmit: PropTypes.func,
  messages: PropTypes.shape({}),
  error: PropTypes.string,
  classes: PropTypes.shape({})
};


AddAllergiesForm.defaultProps = {
  handleSubmit: noop,
  messages: {
    default: 'default message'
  },
  error: undefined,
  classes: {}
};

export default withStyles(styles)(AddAllergiesForm);
