import React, { useEffect, useState } from 'react';
import { Alert } from 'react-bootstrap';
import { getInvestigationUsersByInvestigationId } from '../../api/icat/icatPlus';
import { groupBy } from 'lodash-es';
import axios from 'axios';
import ResponsiveTable from '../Table/ResponsiveTable';
import Loader from '../Loader';
import { useSelector } from 'react-redux';

function ParticipantsPanel(props) {
  const { investigationId } = props;
  const sessionId = useSelector((state) => state.user.sessionId);

  const [state, setState] = useState({});
  const { participants, fetching, error } = state;

  useEffect(() => {
    setState({ fetching: true });

    axios
      .get(getInvestigationUsersByInvestigationId(sessionId, investigationId))
      .then((res) => groupBy(res.data, (user) => user.name))
      .then((participantsById) => {
        setState({
          participants: Object.entries(participantsById).map(([id, users]) => ({
            id,
            name: users[0].fullName,
            role: users.map((user) => user.role).join(', '),
          })),
        });
      })
      .catch(() => {
        setState({ error: true });
      });
  }, [sessionId, investigationId]);

  if (fetching) {
    return <Loader message="Loading participants..." />;
  }

  if (error) {
    return <Alert bsStyle="danger">Unable to retrieve participants</Alert>;
  }

  if (!participants) {
    return null;
  }

  return (
    <ResponsiveTable
      keyField="id"
      data={participants}
      columns={[
        { text: 'id', dataField: 'id', hidden: true, searchable: false },
        { text: 'Name', dataField: 'name' },
        { text: 'Role', dataField: 'role' },
      ]}
    />
  );
}

export default ParticipantsPanel;
