import React, { useState } from 'react';
import styles from './MyAddressesSummary.module.css';
import { LinkContainer } from 'react-router-bootstrap';
import {
  Alert,
  Button,
  Glyphicon,
  HelpBlock,
  Grid,
  Row,
  Col,
} from 'react-bootstrap';
import { useResource, useFetcher } from 'rest-hooks';
import AddressResource from '../../resources/address';
import { useQuery } from '../../helpers/hooks';
import { useHistory } from 'react-router';
import AddressPanel from './AddressPanel';
import AddressFormModal from './AddressFormModal';

function MyAddressesSummary() {
  const [alert, setAlert] = useState();

  const history = useHistory();
  const query = useQuery();
  const isCreating = query.has('new');
  const editingId = query.get('edit');

  const addresses = useResource(AddressResource.listShape(), {});
  const editedAddress = addresses.find((a) => a._id === editingId);

  const createAddress = useFetcher(AddressResource.createShape());
  const editAddress = useFetcher(AddressResource.updateShape());
  const deleteAddress = useFetcher(AddressResource.deleteShape());
  const refetchAddresses = useFetcher(AddressResource.listShape());

  function handleCloseModal() {
    history.push(`/addresses`);
  }

  async function handleSubmit(values) {
    setAlert(undefined);
    try {
      if (!editedAddress) {
        await createAddress(values);
      } else {
        await editAddress(values);
      }

      await refetchAddresses();
      setAlert({
        type: 'success',
        message: `Address ${isCreating ? 'created' : 'saved'}.`,
      });
    } catch (error) {
      setAlert({ type: 'danger', message: `An error occurred.` });
      console.error(error.response);
    }

    handleCloseModal();
  }

  function renderPanelHeader(address) {
    return (
      <div className={styles.addressHeading}>
        <span className={styles.investigation}>
          {address.investigationName}
        </span>
        <div className={styles.actions}>
          <LinkContainer to={`/addresses?edit=${address._id}`}>
            <Button bsSize="xsmall" bsStyle="link" aria-label="Edit">
              <Glyphicon glyph="pencil" />
              <span className={styles.actionLabel}> Edit</span>
            </Button>
          </LinkContainer>
          <Button
            bsSize="xsmall"
            bsStyle="link"
            aria-label="Remove"
            onClick={async () => {
              try {
                await deleteAddress(address);
                setAlert({
                  style: 'success',
                  message: 'Address was removed !',
                });
              } catch (error) {
                setAlert({ type: 'danger', message: `An error occurred.` });
                console.log(error);
              }
            }}
          >
            <Glyphicon glyph="trash" />
            <span className={styles.actionLabel}> Remove</span>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <>
      {(isCreating || editingId) && (
        <AddressFormModal
          address={editedAddress}
          onSubmitAsync={handleSubmit}
          onCloseModal={handleCloseModal}
        />
      )}
      {alert && <Alert bsStyle={alert.style}>{alert.message}</Alert>}
      <Grid fluid>
        <Row>
          <Col sm={24} md={12}>
            <div className={styles.heading}>
              <h3>Addresses</h3>
              <LinkContainer to={`/addresses?new`}>
                <Button bsStyle="primary" aria-label="Create an address">
                  <Glyphicon glyph="plus" /> Add an address
                </Button>
              </LinkContainer>
            </div>
          </Col>
        </Row>
        <Row>
          {addresses.length > 0 ? (
            addresses.map((address) => (
              <Col key={address._id} sm={6} md={3}>
                <AddressPanel
                  header={renderPanelHeader(address)}
                  address={address}
                />
              </Col>
            ))
          ) : (
            <HelpBlock>No address to display.</HelpBlock>
          )}
        </Row>
      </Grid>
    </>
  );
}

export default MyAddressesSummary;
