import axios from 'axios';
import React, { Component } from 'react';
import { Button, Col, Glyphicon, Grid, InputGroup, Row } from 'react-bootstrap';
import { Typeahead } from 'react-bootstrap-typeahead';
import { createInstrumentScientists, getUsers } from '../../api/icat/icatPlus';
import {
  ErrorUserMessage,
  SuccessUserMessage,
} from '../UserMessages/UserMessage';

export default class BeamlineManagerForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {
        fetching: false,
        fetched: false,
        data: [],
      },
      fetching: false,
      usersSelected: [],
      instrumentsSelected: [],
      message: {
        isError: false,
        text: null,
      },
    };
    this.handleClick = this.handleClick.bind(this);
  }

  _renderMenuItemChildren = (option) => [
    <span>{option.fullName}</span>,
    <br />,
  ];

  _renderBeamlineItem = (option) => [<span>{option}</span>, <br />];

  getUsers() {
    axios
      .get(getUsers(this.props.user.sessionId))
      .then((response) => {
        if (response.status === 200) {
          this.setState({
            user: {
              fetching: false,
              fetched: true,
              data: response.data,
            },
          });
        }
      })
      .catch((error) => {
        this.setState({
          message: {
            isError: true,
            text: error.message,
          },
        });
      });
  }

  componentDidMount() {
    this.getUsers();
  }

  handleClick() {
    this.setState({
      fetching: true,
    });

    axios
      .put(createInstrumentScientists(this.props.user.sessionId), {
        usernames: this.state.usersSelected.map((u) => u.name),
        instrumentnames: this.state.instrumentsSelected,
      })
      .then((response) => {
        this.setState({
          fetching: false,
          usersSelected: [],
          instrumentsSelected: [],
          message: {
            isError: false,
            text:
              response.status === 200
                ? 'User(s) have been added correctly as beamline managers'
                : 'Oopps, something might be wrong',
          },
        });
        this.props.fetchInstrumentScientistsBySessionId(
          this.props.user.sessionId
        );
      })
      .catch((error) => {
        this.setState({
          fetching: false,
          message: {
            isError: true,
            text: error.message,
          },
        });
      });
  }

  render() {
    const users = this.state.user.data.filter((u) => !!u.fullName);

    return (
      <Grid fluid>
        <Row>
          <Col xs={12} md={3}>
            <InputGroup>
              <InputGroup.Addon>
                <span>
                  {' '}
                  <Glyphicon glyph="user" /> Users
                </span>
              </InputGroup.Addon>
              <Typeahead
                id="typeAheadUsers"
                labelKey="fullName"
                renderMenuItemChildren={this._renderMenuItemChildren}
                multiple
                onChange={(usersSelected) => {
                  this.setState({ usersSelected });
                }}
                selected={this.state.usersSelected}
                options={users}
                placeholder="Choose a user..."
              />
            </InputGroup>
          </Col>
          <Col xs={12} md={3}>
            <InputGroup>
              <InputGroup.Addon>
                <span>
                  {' '}
                  <Glyphicon glyph="facetime-video" /> Beamlines
                </span>
              </InputGroup.Addon>
              <Typeahead
                id="typeAheadBeamlines"
                renderMenuItemChildren={this._renderBeamlineItem}
                multiple
                onChange={(instrumentsSelected) => {
                  this.setState({ instrumentsSelected });
                }}
                selected={this.state.instrumentsSelected}
                options={this.props.instrumentScientists.instrumentNames}
                placeholder="Choose a beamline..."
              />
            </InputGroup>
          </Col>
          <Col xs={12} md={1}>
            <Button
              bsStyle="primary"
              type="submit"
              disabled={
                this.state.fetching ||
                this.state.usersSelected.length === 0 ||
                this.state.instrumentsSelected.length === 0
              }
              onClick={this.handleClick}
            >
              {this.state.fetching ? 'Adding' : 'Add'}
            </Button>
          </Col>
          <Col xs={12} md={5}>
            {this.state.message.text && this.state.message.isError && (
              <ErrorUserMessage text={this.state.message.text} />
            )}
            {this.state.message.text && !this.state.message.isError && (
              <SuccessUserMessage text={this.state.message.text} />
            )}
          </Col>
        </Row>
      </Grid>
    );
  }
}
