import React from 'react';
import { Button, Glyphicon } from 'react-bootstrap';
import { useHistory } from 'react-router';
import { useFetcher } from 'rest-hooks';
import { isEditable } from '../../helpers/statusUtils';
import ParcelResource from '../../resources/parcel';
import DownloadLabelButton from './DownloadLabelButton';
import styles from './ParcelHeader.module.css';
import { Link } from 'react-router-dom';

function ParcelHeader(props) {
  const { parcel, setAlert } = props;
  const { shipmentId, investigationId, _id } = parcel;
  const history = useHistory();

  const deleteParcel = useFetcher(ParcelResource.deleteShape());

  return (
    <div className={styles.parcelHeader}>
      <div>
        <h2>
          Parcel <b>{parcel.name}</b>
        </h2>
        <h4 className={styles.investigation}>
          Investigation{' '}
          <Link to={`/investigation/${investigationId}/shipping`}>
            {parcel.investigationName}
          </Link>
        </h4>
      </div>
      <div>
        <DownloadLabelButton className={styles.parcelAction} parcel={parcel} />
        <Button
          className={styles.parcelAction}
          bsStyle="danger"
          onClick={async () => {
            try {
              await deleteParcel(
                { shipmentId, parcelId: _id, investigationId },
                { _id }
              );
              history.push(`/investigation/${investigationId}/shipping`);
            } catch (error) {
              setAlert({
                type: 'danger',
                message: `An error occurred. ${error.message}`,
              });
              console.error(error.response);
            }
          }}
          disabled={!isEditable(parcel)}
        >
          <Glyphicon glyph="remove" />
          <span style={{ margin: 10 }}>Delete</span>
        </Button>
      </div>
    </div>
  );
}

export default ParcelHeader;
