import React, { useState } from 'react';
import {
  Alert,
  Button,
  Col,
  ControlLabel,
  Form,
  FormControl,
  FormGroup,
  Glyphicon,
  Grid,
  Modal,
  Panel,
  Row,
} from 'react-bootstrap';
import { useForm, FormProvider } from 'react-hook-form';
import { useSelector } from 'react-redux';
import FieldAlert from '../Form/FieldAlert';
import TextFieldGroup from '../Form/TextFieldGroup';
import styles from './AddressFormModal.module.css';

function AddressFormModal(props) {
  const { investigation, address, onSubmitAsync, onCloseModal } = props;
  const userInvestigations = useSelector(
    (state) => state.myInvestigations.data
  );

  const methods = useForm({ defaultValues: address });
  const { handleSubmit, errors, register, formState } = methods;

  const { isSubmitting } = formState;
  const [submitError, setSubmitError] = useState();

  async function handleFormSubmit(values) {
    try {
      setSubmitError(undefined);
      await onSubmitAsync(values);
    } catch (error) {
      setSubmitError(
        `An error occurred while ${
          address ? 'saving' : 'creating'
        } the address: ${error}`
      );
    }
  }

  return (
    <Modal
      show
      backdrop="static"
      bsSize="large"
      aria-labelledby="address-modal-title"
      onHide={onCloseModal}
    >
      <Modal.Header closeButton>
        <Modal.Title id="address-modal-title">
          {address ? 'Edit' : 'Create'} address
        </Modal.Title>
      </Modal.Header>

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

        <Form>
          <FormProvider {...methods}>
            {address && <input name="_id" type="hidden" ref={register} />}

            {investigation ? (
              <input
                name="investigationId"
                type="hidden"
                defaultValue={investigation.id}
                ref={register}
              />
            ) : (
              <FormGroup controlId="formInvestigation">
                <div className={styles.row}>
                  <ControlLabel className={styles.proposalLabel}>
                    Proposal
                  </ControlLabel>
                  <div>
                    <FormControl
                      name="investigationId"
                      componentClass="select"
                      placeholder="Select a proposal"
                      inputRef={register({ required: true })}
                    >
                      {userInvestigations &&
                        userInvestigations.map((investigation) => (
                          <option
                            key={investigation.id}
                            value={investigation.id}
                          >
                            {investigation.name}
                          </option>
                        ))}
                    </FormControl>
                  </div>
                  {errors.investigationId && (
                    <FieldAlert
                      fieldLabel="Proposal"
                      error={errors.investigationId}
                    />
                  )}
                </div>
              </FormGroup>
            )}

            <Panel>
              <Panel.Heading>
                <Glyphicon glyph="user" /> Contact Information
              </Panel.Heading>
              <Panel.Body>
                <Grid fluid>
                  <Row>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{ required: true }}
                        name="name"
                        label="First name"
                        type="text"
                      />
                    </Col>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{ required: true }}
                        name="surname"
                        label="Last name"
                        type="text"
                      />
                    </Col>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{ required: true }}
                        name="email"
                        type="email"
                      />
                    </Col>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{
                          required: true,
                          pattern: /\+?\d+/,
                          maxLength: 20,
                        }}
                        name="phoneNumber"
                        label="Phone number"
                        type="tel"
                      />
                    </Col>
                  </Row>
                </Grid>
              </Panel.Body>
            </Panel>

            <Panel>
              <Panel.Heading>
                <Glyphicon glyph="envelope" /> Address
              </Panel.Heading>
              <Panel.Body>
                <Grid fluid>
                  <Row>
                    <Col xs={12} md={6}>
                      <TextFieldGroup
                        name="companyName"
                        label="Institution"
                        type="text"
                      />
                    </Col>
                  </Row>
                </Grid>
                <Grid fluid>
                  <Row>
                    <Col xs={12} md={9}>
                      <TextFieldGroup
                        registerOptions={{ required: true }}
                        name="address"
                        type="textarea"
                      />
                    </Col>
                  </Row>
                </Grid>
                <Grid fluid>
                  <Row>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{
                          required: true,
                          pattern: /\d+/,
                          maxLength: 7,
                        }}
                        name="postalCode"
                        label="Postcode"
                        type="text"
                      />
                    </Col>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{ required: true }}
                        name="city"
                        type="text"
                        errors={errors}
                      />
                    </Col>
                    <Col xs={12} md={3}>
                      <TextFieldGroup
                        registerOptions={{ required: true }}
                        name="country"
                        type="text"
                        errors={errors}
                      />
                    </Col>
                  </Row>
                </Grid>
              </Panel.Body>
            </Panel>
          </FormProvider>
        </Form>
      </Modal.Body>

      <Modal.Footer>
        <Button bsStyle="link" onClick={onCloseModal}>
          Cancel
        </Button>
        <Button
          bsStyle="success"
          disabled={isSubmitting}
          onClick={handleSubmit(handleFormSubmit)}
        >
          {`${address ? 'Sav' : 'Creat'}${isSubmitting ? 'ing...' : 'e'}`}
        </Button>
      </Modal.Footer>
    </Modal>
  );
}

export default AddressFormModal;
