import React, {useState} from "react";
import useAuth from "../../Hooks/auth";
import {
  Button,
  Col,
  Form,
  FormGroup,
  Input,
  InputGroup,
  InputGroupAddon,
  Label,
  Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
  Row
} from "reactstrap";
import PermissionsModal from "./PermissionsModal";
import {saveGroupMetadata} from "../../Helpers/groups";

function GroupPropertiesModal({id, nValue, permissions, onClose}) {
  const {users} = useAuth();
  const [name, setName] = useState(nValue);
  const [permUserId, setPermUserId] = useState(null);
  const [permModal, setPermModal] = useState(false);

  function permissionFor(userId) {
    const perm = permissions.find(p => p.userId === userId);

    return typeof perm !== "undefined"
      ? perm
      : null;
  }

  return (
    <Modal isOpen={true}>
      <ModalHeader>Endre gruppe</ModalHeader>
      <ModalBody style={{margin: "0 auto"}}>
        <Form>
          <FormGroup row>
            <Label sm={3} for="text-name">
              Navn:
            </Label>
            <Col sm={9}>
              <Input type="text"
                     id="text-name"
                     name="power"
                     value={name}
                     onChange={e => setName(e.target.value)}/>
            </Col>
          </FormGroup>
          <FormGroup row>
            <Label sm={3}>
              Tilgang:
            </Label>
            <Col sm={9}>
              {users.map(user => {
                const permission = permissionFor(user.id);
                const btnColor = permission !== null ? "secondary" : "success";
                const btnLabel = permission !== null ? "Endre" : "Opprett";

                return (
                  <Row>
                    <InputGroup className="mb-2">
                      <Input className="permission" disabled value={user.name}/>
                      <InputGroupAddon addonType="prepend">
                        <Button color={btnColor} onClick={() => {
                          setPermUserId(user.id);
                          setPermModal(true);
                        }}>{btnLabel}</Button>
                      </InputGroupAddon>
                    </InputGroup>
                  </Row>
                )
              })}
            </Col>
          </FormGroup>
        </Form>
      </ModalBody>
      <ModalFooter>
        <Button color="primary"
                onClick={() => {
                  saveGroupMetadata(id, name);
                  onClose();
                }}
        >
          Lagre
        </Button>
        {" "}
        <Button color="secondary" onClick={onClose}>Avbryt</Button>
      </ModalFooter>
      {permModal && (
        <PermissionsModal permissions={permissionFor(permUserId)}
                          groupId={id}
                          userId={permUserId}
                          onClose={() => setPermModal(false)}
        />
      )}
    </Modal>
  );
}

export default GroupPropertiesModal;
