import React, { useEffect } from 'react';
import { Col, Grid, Row } from 'react-bootstrap';
import { useParams } from 'react-router';
import { useInvestigation } from '../helpers/hooks';
import { useDispatch, useSelector } from 'react-redux';
import { setBreadCrumbs } from '../actions/breadcrumbs';
import TabContainerMenu from '../components/TabContainerMenu/TabContainerMenu';
import Loader from '../components/Loader';
import DatasetTable from '../components/Dataset/DatasetTable';
import { removeDatasetById, addDatasetById } from '../actions/selection';
import PageNotFound from './PageNotFound';
import { fetchDatasetsByInvestigationId } from '../actions/datasets';

function DatasetsPage() {
  const { investigationId } = useParams();
  const { investigation, fetching } = useInvestigation(investigationId);
  const sessionId = useSelector((state) => state.user.sessionId);
  const datasets = useSelector((state) => state.datasets);
  const selection = useSelector((state) => state.selection);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchDatasetsByInvestigationId(sessionId, investigationId));

    if (investigation) {
      dispatch(
        setBreadCrumbs([
          { name: investigation.visitId.toUpperCase() },
          { badge: investigation.name, name: investigation.summary },
        ])
      );
    }

    // `investigation` object can be duplicated in store, so we use `investigation.id` as effect dependency
  }, [dispatch, investigationId, sessionId, investigation?.id]); // eslint-disable-line react-hooks/exhaustive-deps

  if (!investigation) {
    return fetching ? (
      <Loader message="Loading investigation..." spacedOut />
    ) : (
      <PageNotFound />
    );
  }

  const expanded =
    investigation.visitId === 'publisher' ? datasets.data.map((d) => d.id) : [];

  return (
    <Grid fluid>
      <Row>
        <Col sm={12}>
          <TabContainerMenu />
          {datasets.fetching ? (
            <Loader message="Loading datasets..." spacedOut />
          ) : (
            <DatasetTable
              selection={selection}
              removeDatasetById={(...params) =>
                dispatch(removeDatasetById(...params))
              }
              addDatasetById={(...params) =>
                dispatch(addDatasetById(...params))
              }
              sessionId={sessionId}
              expanded={expanded}
              datasets={datasets.data}
            />
          )}
        </Col>
      </Row>
    </Grid>
  );
}

export default DatasetsPage;
