import React, {useState} from "react";
import {Button, Card, CardBody, CardFooter, CardHeader} from "reactstrap";
import useBridges from "../Hooks/bridge";
import BridgeModal from "./Modals/BridgeModal";
import useLights from "../Hooks/lights";
import Loading from "./Loading";
import BridgeLight from "./BridgeLight";

function Bridge({addr, driver, id, name}) {
  const {forgetBridge, discoverLights} = useBridges();
  const {lightsByBridge} = useLights();
  const [modal, setModal] = useState(false);

  function edit() {
    setModal(true);
  }

  function unEdit() {
    setModal(false);
  }

  function forget() {
    if (window.confirm(`Vil du virkelig glemme bruen "${name}"?`)) {
      forgetBridge(id);
    }
  }

  function discover() {
    discoverLights(id);
  }

  const lights = lightsByBridge(id);
  const hasLights = lights !== null;

  return (
    <Card className="mt-3">
      <CardHeader>{name} ({driver}, {addr})</CardHeader>
      <CardBody>
        {hasLights ? lights.map(l => <BridgeLight key={l.id} {...l} />) : <Loading/>}
      </CardBody>
      <CardFooter>
        <Button color="info" onClick={discover}>Oppdag lys</Button>
        {" "}
        <Button color="secondary" onClick={edit}>Endre</Button>
        {" "}
        <Button color="danger" onClick={forget}>Glem</Button>
      </CardFooter>
      {modal && <BridgeModal bridge={{addr, driver, id, name}} onCancel={unEdit} />}
    </Card>
  );
}

export default Bridge;
