import React, { useState } from 'react';
import { Alert, Button, HelpBlock, Modal } from 'react-bootstrap';
import { useForm } from 'react-hook-form';
import UI from '../../config/ui/config';

function DangerousGoodsModal(props) {
  const { onConfirm, onCloseModal, isProcessing } = props;
  const [submitError, setSubmitError] = useState();

  const { handleSubmit } = useForm();

  function onSubmit(values) {
    try {
      onConfirm(values);
    } catch (error) {
      setSubmitError(`There was an error while updating the parcel: ${error}`);
    }
  }

  return (
    <Modal show aria-labelledby="parcel-modal-title" onHide={onCloseModal}>
      <Modal.Header closeButton>
        <Modal.Title id="parcel-modal-title">
          Does the parcel contain dangerous goods ?
        </Modal.Title>
      </Modal.Header>

      <Modal.Body>
        {submitError && <Alert bsStyle="danger">{submitError}</Alert>}
        <HelpBlock>{UI.dangerousGoodsHelp}</HelpBlock>
      </Modal.Body>

      <Modal.Footer>
        {isProcessing ? (
          <Button bsStyle="warning" disabled={true}>
            Processing...
          </Button>
        ) : (
          <>
            <Button
              bsStyle="warning"
              onClick={() =>
                handleSubmit(onSubmit({ containsDangerousGoods: true }))
              }
            >
              Yes
            </Button>
            <Button
              bsStyle="warning"
              onClick={() =>
                handleSubmit(onSubmit({ containsDangerousGoods: false }))
              }
            >
              No
            </Button>
          </>
        )}
      </Modal.Footer>
    </Modal>
  );
}

export default DangerousGoodsModal;
