import axios from 'axios';
import React from 'react';
import { Button } from 'react-bootstrap';
import { createInstrumentScientists } from '../../api/icat/icatPlus';
import Loader from '../Loader';
import ResponsiveTable from '../Table/ResponsiveTable';

class InstrumentScientistTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fetching: false,
      fetched: false,
    };

    this.handleRevokeClick = this.handleRevokeClick.bind(this);
  }

  getColumns() {
    return [
      {
        text: 'id',
        dataField: 'id',
        hidden: true,
      },
      {
        text: 'User',
        dataField: 'fullName',
        sort: true,
      },
      {
        text: 'Beamline',
        dataField: 'instrumentName',
        sort: true,
      },
      {
        dataField: 'buttons',
        text: '',
        formatExtraData: this,
        formatter: this.renderButtons,
      },
    ];
  }

  handleRevokeClick = (instrumentscientistsid) => {
    this.setState({
      fetching: true,
    });

    axios
      .delete(createInstrumentScientists(this.props.user.sessionId), {
        data: {
          instrumentscientistsid: [instrumentscientistsid],
        },
      })
      .then(() => {
        this.setState({
          fetching: false,
        });
        this.props.fetchInstrumentScientistsBySessionId(
          this.props.user.sessionId
        );
      })
      .catch((error) => {
        this.setState({
          fetching: false,
          message: {
            isError: true,
            text: error.message,
          },
        });
      });
  };
  renderButtons = (_, row) => (
    <Button bsStyle="danger" onClick={() => this.handleRevokeClick(row.id)}>
      Revoke
    </Button>
  );

  render() {
    const data = this.props.instrumentScientists.sort(
      (a, b) => a.instrument.name > b.instrument.name
    );

    if (this.props.fetching || this.state.fetching) {
      return <Loader message="Loading beamline managers..." inPanel />;
    }

    return (
      <ResponsiveTable
        data={data.map((is) => ({
          id: is.id,
          instrumentName: is.instrument.name,
          fullName: is.user.fullName,
        }))}
        columns={this.getColumns()}
        pageOptions={{
          sizePerPage: 100,
        }}
      />
    );
  }
}

export default InstrumentScientistTable;
