import React, {useState} from "react";
import {Button, Card, CardBody, CardFooter, CardHeader, ListGroup} from "reactstrap";
import useLights from "../Hooks/light";
import Light from "./Light";
import Loading from "./Loading";
import {deleteGroup} from "../Helpers/groups";
import ColorModal from "./Modals/ColorModal";
import {changeColor} from "../Helpers/lights";
import GroupPropertiesModal from "./Modals/GroupPropertiesModal";
import useAuth from "../Hooks/auth";

function Group({id, name, permissions}) {
  const {user} = useAuth();
  const lights = useLights({groupId: id});

  const [colorModal, setColorModal] = useState(false);
  const [propModal, setPropModal] = useState(false);

  const ready = lights !== null;
  const noLights = ready && lights.length === 0;
  const hasLights = ready && lights.length > 0;

  if (id === 0 && noLights) {
    return <></>;
  }

  function onDelete() {
    if (window.confirm(`Vil du virkelig fjerne "${name}"?`)) {
      deleteGroup(id);
    }
  }

  let cValue = null;
  let bValue = null;
  let pValue = null;
  if (hasLights) {
    cValue = lights[0].color;
    bValue = lights[0].brightness;
    pValue = lights[0].on;
  }

  function iCan(name) {
    if (permissions === null) {
      return false;
    }

    const perm = permissions.find(p => p.userId === user.id);

    return typeof perm !== "undefined"
      ? perm[name]
      : false;
  }

  return (
    <Card className="mt-3">
      <CardHeader>{name}</CardHeader>
      <CardBody>
        {ready
          ? <ListGroup>{lights.map(light => <Light key={light.id} {...light} />)}</ListGroup>
          : <Loading/>}
      </CardBody>
      {(iCan("manage") || iCan("write") || iCan("delete")) && (
        <CardFooter>
          {iCan("manage") && (
            <Button color="primary" onClick={() => setPropModal(true)}>Detaljer</Button>
          )}
          {" "}
          {hasLights && iCan("write") && (
            <Button color="secondary" onClick={() => setColorModal(true)}>Skift farger</Button>
          )}
          {" "}
          {iCan("delete") && (id > 0) && (
            <Button color="danger" onClick={onDelete}>Fjern</Button>
          )}
        </CardFooter>
      )}
      {colorModal && (
        <ColorModal cValue={cValue}
                    bValue={bValue}
                    pValue={pValue}
                    onConfirm={(color, brightness, power) => {
                      lights.forEach(light => {
                        changeColor(light.id, color, brightness, power);
                        setColorModal(false);
                      });
                    }}
                    onCancel={() => setColorModal(false)}
        />
      )}
      {propModal && (
        <GroupPropertiesModal id={id}
                              nValue={name}
                              permissions={permissions}
                              onClose={() => setPropModal(false)}
        />
      )}
    </Card>
  );
}

export default Group;
