import React from 'react';
import { Button, Grid } from 'react-bootstrap';
import { useHistory } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import { useFetcher } from 'rest-hooks';
import { useQuery } from '../../helpers/hooks';
import ShipmentResource from '../../resources/shipment';
import ShipmentSummary from './ShipmentSummary';
import ShippingForm from './ShippingForm';

function ShipmentSection(props) {
  const {
    investigation,
    shipment,
    defaultShippingAddress,
    defaultReturnAddress,
  } = props;
  const apiParams = { investigationId: investigation.id };

  const history = useHistory();
  const query = useQuery();
  const isConfiguring = !shipment || query.has('configure');

  const createShipment = useFetcher(ShipmentResource.createShape());
  const editShipment = useFetcher(ShipmentResource.updateShape());
  const refetchShipments = useFetcher(ShipmentResource.listShape());

  async function handleSubmit(values) {
    if (!shipment) {
      await createShipment(apiParams, values);
    } else {
      await editShipment(apiParams, values);
    }

    await refetchShipments(apiParams);
    history.push(`/investigation/${investigation.id}/shipping`);
  }

  return (
    <Grid style={{ marginLeft: 0 }} fluid>
      <div className="actions-heading">
        <h3>Shipping configuration</h3>
        {!isConfiguring && (
          <LinkContainer
            to={`/investigation/${investigation.id}/shipping?configure`}
          >
            <Button bsStyle="primary">Edit</Button>
          </LinkContainer>
        )}
      </div>

      {isConfiguring ? (
        <ShippingForm
          investigation={investigation}
          shipment={shipment}
          defaultShippingAddress={defaultShippingAddress}
          defaultReturnAddress={defaultReturnAddress}
          onSubmitAsync={handleSubmit}
        />
      ) : (
        <ShipmentSummary
          shipment={shipment}
          defaultShippingAddress={defaultShippingAddress}
          defaultReturnAddress={defaultReturnAddress}
        />
      )}
    </Grid>
  );
}

export default ShipmentSection;
