import React, { Suspense, useEffect } from 'react';
import { Alert, Col, Grid, Row } from 'react-bootstrap';
import { useDispatch } from 'react-redux';
import { useParams } from 'react-router';
import { NetworkErrorBoundary } from 'rest-hooks';
import { setBreadCrumbs } from '../actions/breadcrumbs';
import Loader from '../components/Loader';
import ShippingPanel from '../components/Shipping/ShippingPanel';
import TabContainerMenu from '../components/TabContainerMenu/TabContainerMenu';
import { useInvestigation } from '../helpers/hooks';
import PageNotFound from './PageNotFound';

function ShippingPage() {
  const { investigationId } = useParams();
  const { investigation, fetching } = useInvestigation(investigationId);
  const dispatch = useDispatch();

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

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

  return (
    <Grid fluid>
      <Row>
        <Col sm={12}>
          <TabContainerMenu />
          <Suspense
            fallback={<Loader message="Loading shipping data..." spacedOut />}
          >
            <NetworkErrorBoundary
              fallbackComponent={({ error }) => (
                <Alert bsStyle="warning" style={{ marginTop: 16 }}>
                  {error.status === 403
                    ? 'You are not allowed to manage shipping for this investigation.'
                    : `An error occured: ${error.message}`}
                </Alert>
              )}
            >
              <ShippingPanel investigation={investigation} />
            </NetworkErrorBoundary>
          </Suspense>
        </Col>
      </Row>
    </Grid>
  );
}

export default ShippingPage;
