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

function DOIPage() {
  const { prefix, suffix } = useParams();
  const doi = `${prefix}/${suffix}`;

  const sessionId = useSelector((state) => state.user.sessionId);
  const datasets = useSelector((state) => state.datasets);
  const selection = useSelector((state) => state.selection);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchDatasetsByDOI(sessionId, doi));
    dispatch(
      setBreadCrumbs([
        { name: 'Open Data', link: '/public' },
        { name: '', badge: doi },
      ])
    );
  }, [dispatch, doi, sessionId]);

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

export default DOIPage;
