import React, {useState} from "react";
import {Button, Col, Form, FormGroup, Input, Label, Modal, ModalBody, ModalFooter, ModalHeader} from "reactstrap";
import useBridges from "../../Hooks/bridge";
import Loading from "../Loading";

function BridgeModal({onCancel, bridge = null}) {
  const {addBridge, editBridge} = useBridges();

  const edit = bridge !== null;

  const [name, setName] = useState(edit ? bridge.name : "");
  const [driver, setDriver] = useState(edit ? bridge.driver : "");
  const [addr, setAddr] = useState(edit ? bridge.addr : "");

  const [waiting, setWaiting] = useState(false);

  function onConfirm() {
    if (edit) {
      editBridge(bridge.id, name);
    } else {
      setWaiting(true);
      addBridge(name, driver, addr, (result) => {
        if (!result) {
          alert("Noe gikk galt");
        }

        setWaiting(false);
        onCancel();
      });
    }
  }

  return (
    <Modal isOpen={true}>
      <ModalHeader>{edit ? "Bruegenskaper" : "Ny bru"}</ModalHeader>
      <ModalBody>
        {waiting ? (
          <Loading/>
        ) : (
          <Form>
            <FormGroup row>
              <Label sm={3} for="text-name">
                Navn:
              </Label>
              <Col sm={9}>
                <Input type="text"
                       id="text-name"
                       name="name"
                       value={name}
                       onChange={e => setName(e.target.value)}
                />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Label sm={3} for="text-driver">
                Driver:
              </Label>
              <Col sm={9}>
                <Input type="text"
                       id="text-driver"
                       name="driver"
                       value={driver}
                       onChange={e => setDriver(e.target.value)}
                       disabled={edit}
                />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Label sm={3} for="text-name">
                Adresse:
              </Label>
              <Col sm={9}>
                <Input type="text"
                       id="text-addr"
                       name="addr"
                       value={addr}
                       onChange={e => setAddr(e.target.value)}
                       disabled={edit}
                />
              </Col>
            </FormGroup>
          </Form>
        )}
        </ModalBody>
      <ModalFooter>
        <Button color="primary" disabled={waiting} onClick={onConfirm}>Bekreft</Button>
        {" "}
        <Button color="secondary" disabled={waiting} onClick={onCancel}>Avbryt</Button>
      </ModalFooter>
    </Modal>
  );
}

export default BridgeModal;
