import axios from 'axios';
import React from 'react';
import {
  Glyphicon,
  Button,
  ControlLabel,
  Form,
  FormControl,
  FormGroup,
  Label,
  MenuItem,
  Panel,
  SplitButton,
} from 'react-bootstrap';
import { getMintDOI } from '../../api/icat/icatPlus';
import BootstrapTable2 from 'react-bootstrap-table-next';

class DOIForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      authors: [],
      investigationUsers: [],
      selectedAuthors: [],
      fetching: false,
      fetched: false,
    };

    this.addAuthor = this.addAuthor.bind(this);
    this.handleOnSelectUser = this.handleOnSelectUser.bind(this);
    this.handleOnSelectAllUsers = this.handleOnSelectAllUsers.bind(this);
    this.handleDeleteClick = this.handleDeleteClick.bind(this);

    this.authorCount = 0;
  }

  /**
   * Add an author to the table
   */
  addAuthor(investigationUser) {
    const authors = this.state.authors;
    if (!investigationUser.fullName) {
      authors.push({
        name: this.name.value,
        surname: this.surname.value,
        id: `${this.name.value}_${this.surname.value}_${this.authorCount++}`,
      });
    } else {
      const name = investigationUser.fullName.split(' ')[0];
      const surname = investigationUser.fullName.replace(
        investigationUser.fullName.split(' ')[0],
        ''
      );
      authors.push({
        name,
        surname,
        id: `${name}_${surname}_${this.authorCount++}`,
      });
    }
    this.setState({
      authors,
    });
  }

  handleOnSelectUser(row, isSelected) {
    if (isSelected) {
      this.setState({
        selectedAuthors: [...this.state.selectedAuthors, row.id],
      });
    } else {
      this.setState({
        selectedAuthors: this.state.selectedAuthors.filter((x) => x !== row.id),
      });
    }
  }

  handleOnSelectAllUsers(isSelected, rows) {
    if (isSelected) {
      this.setState({ selectedAuthors: rows.map((r) => r.id) });
    } else {
      this.setState({ selectedAuthors: [] });
    }
  }

  handleDeleteClick() {
    const { authors, selectedAuthors } = this.state;
    this.setState({
      authors: authors.filter((author) => !selectedAuthors.includes(author.id)),
      selectedAuthors: [],
    });
  }

  /**
   * This method will get the params from the form and will cal to ICAT+ to mint a new DOI
   */
  mint() {
    const authors = this.state.authors;
    const title = this.title.value;
    const abstract = this.abstract.value;
    const datasetIdList = [];
    for (let i = 0; i < this.props.datasets.length; i++) {
      datasetIdList.push(this.props.datasets[i].id);
    }
    const url = getMintDOI(this.props.sessionId);
    axios
      .post(url, {
        title,
        abstract,
        datasetIdList,
        authors,
      })
      .then((response) => {
        if (response) {
          if (response.data) {
            if (response.data.message) {
              alert(`Your DOI has been created ${response.data.message}`);
            }
          }
        }
      })
      .catch((error) => {
        if (error) {
          if (error.response) {
            if (error.response.data) {
              if (error.response.data.message) {
                alert(error.response.data.message);
              }
            }
          }
        }
      });
  }

  renderButton() {
    return (
      <SplitButton
        bsStyle="default"
        title="Add author"
        style={{ width: 100 }}
        onClick={this.addAuthor}
      >
        {this.props.investigationUsers.map(function (user) {
          const bsStyleRole =
            user.role === 'Principal investigator' ? 'primary' : 'default';
          return (
            <MenuItem
              style={{ width: 350 }}
              eventKey={user}
              onSelect={this.addAuthor}
            >
              <span style={{ marginLeft: 10 }}>{user.fullName} </span>
              <Label bsStyle="info" style={{ marginLeft: 20 }}>
                {user.investigationName}
              </Label>
              <Label bsStyle={bsStyleRole} style={{ marginLeft: 10 }}>
                {user.role}
              </Label>
            </MenuItem>
          );
        }, this)}
        <MenuItem divider />
      </SplitButton>
    );
  }

  render() {
    return (
      <Form>
        <FormGroup controlId="formControlsTextarea">
          <ControlLabel>
            Title <Mandatory />
          </ControlLabel>
          <FormControl
            inputRef={(ref) => {
              this.title = ref;
            }}
            componentClass="textarea"
            placeholder=""
          />
        </FormGroup>

        <FormGroup controlId="formControlsTextarea">
          <ControlLabel>
            Abstract <Mandatory />
          </ControlLabel>
          <FormControl
            inputRef={(ref) => {
              this.abstract = ref;
            }}
            componentClass="textarea"
            placeholder=""
          />
        </FormGroup>
        <br />
        <Panel bsStyle="primary">
          <Panel.Heading>
            <Panel.Title>Authors</Panel.Title>
          </Panel.Heading>

          <Panel.Body>
            <Form inline>
              <FormGroup controlId="formInlineName">
                <ControlLabel>Name</ControlLabel>{' '}
                <FormControl
                  inputRef={(ref) => {
                    this.name = ref;
                  }}
                  type="text"
                />
              </FormGroup>{' '}
              <FormGroup controlId="formInlineEmail" style={{ marginLeft: 10 }}>
                <ControlLabel>Surname</ControlLabel>{' '}
                <FormControl
                  inputRef={(ref) => {
                    this.surname = ref;
                  }}
                />
              </FormGroup>{' '}
              {this.renderButton()}
            </Form>

            <br />
            <Button
              bsStyle="warning"
              style={{ marginBottom: 10 }}
              disabled={this.state.selectedAuthors.length === 0}
              onClick={this.handleDeleteClick}
            >
              <Glyphicon glyph="trash" /> Delete
            </Button>
            <BootstrapTable2
              keyField="id"
              data={this.state.authors}
              columns={[
                { dataField: 'id', text: '', hidden: true },
                { dataField: 'name', text: 'Name' },
                { dataField: 'surname', text: 'Surname' },
              ]}
              selectRow={{
                mode: 'checkbox',
                clickToSelect: true,
                selected: this.state.selectedAuthors,
                onSelect: this.handleOnSelectUser,
                onSelectAll: this.handleOnSelectAllUsers,
              }}
              striped
              hover
              condensed
            />
          </Panel.Body>
        </Panel>
        <br />
        <Button
          onClick={this.mint.bind(this)}
          className="btn btn-primary pull-right"
        >
          Mint
        </Button>
      </Form>
    );
  }
}

class Mandatory extends React.Component {
  render() {
    return <span style={{ color: 'red' }}>*</span>;
  }
}

export default DOIForm;
