import React, {useState} from "react";
import {Button, CustomInput, FormGroup, Modal, ModalBody, ModalFooter, ModalHeader} from "reactstrap";
import {savePermissions} from "../../Helpers/groups";

function PermissionsModal({groupId, userId, permissions, onClose}) {
  function getPermission(type) {
    if (permissions === null || typeof permissions[type] === "undefined") {
      return false;
    }

    return permissions[type];
  }

  const [read, setRead] = useState(getPermission("read"));
  const [write, setWrite] = useState(getPermission("write"));
  const [create, setCreate] = useState(getPermission("create"));
  const [remove, setRemove] = useState(getPermission("delete"));
  const manage = getPermission("manage");

  return (
    <Modal isOpen={true}>
      <ModalHeader>Endre gruppe</ModalHeader>
      <ModalBody style={{margin: "0 auto"}}>
        <FormGroup className="perm-switch">
          <CustomInput type="switch"
                       id="switch-read"
                       name="read"
                       label="Les"
                       checked={read}
                       onChange={e => setRead(e.target.checked)}/>
        </FormGroup>
        <FormGroup className="perm-switch">
          <CustomInput type="switch"
                       id="switch-write"
                       name="write"
                       label="Skriv"
                       checked={write}
                       onChange={e => setWrite(e.target.checked)}/>
        </FormGroup>
        <FormGroup className="perm-switch">
          <CustomInput type="switch"
                       id="switch-create"
                       name="create"
                       label="Opprett"
                       checked={create}
                       onChange={e => setCreate(e.target.checked)}/>
        </FormGroup>
        <FormGroup className="perm-switch">
          <CustomInput type="switch"
                       id="switch-remove"
                       name="remove"
                       label="Slett"
                       checked={remove}
                       onChange={e => setRemove(e.target.checked)}/>
        </FormGroup>
        <FormGroup className="perm-switch">
          <CustomInput type="switch"
                       id="switch-manage"
                       name="manage"
                       label="Forvalte"
                       checked={manage}
                       disabled/>
        </FormGroup>
      </ModalBody>
      <ModalFooter>
        <Button color="primary"
                onClick={() => {
                  savePermissions(
                    groupId,
                    userId,
                    {read, write, delete: remove, create});
                  onClose();
                }}
        >
          Lagre
        </Button>
        {" "}
        <Button color="secondary" onClick={onClose}>Avbryt</Button>
      </ModalFooter>
    </Modal>
  );
}

export default PermissionsModal;
