import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Box,
  Card,
  CardContent,
  Checkbox,
  CircularProgress,
  Divider,
  FormControl,
  FormControlLabel,
  FormGroup,
  //FormLabel,
  Grid2 as Grid,
  Theme,
  Tooltip,
  Typography
} from "@mui/material";
import { lightGreen } from "@mui/material/colors";
import { ExpandMore, Warning } from "@mui/icons-material";
import MeasurementsChart from "charts/MeasurementsChart";
//import { GraphOrientation } from "common/Graph";
//import RangeInput, { Range } from "common/RangeInput";
import { GetDefaultDateRange } from "common/time/DateRange";
//import DateSelect from "common/time/DateSelect";
//import MeasurementSummary from "component/MeasurementSummary";
import { grainName } from "grain";
import { useMobile } from "hooks";
import { cloneDeep } from "lodash";
import { Component, Interaction } from "models";
import { UnitMeasurement } from "models/UnitMeasurement";
import moment from "moment";
//import { deviceComponentID } from "pbHelpers/Component";
import {
  extension,
  //getComponentVisual,
  //GetNumNodes,
  GetNumNodesFromUnitMeasurement,
  GraphFilters
} from "pbHelpers/ComponentType";
import { binSplitAt, isBinSplit } from "pbHelpers/ComponentTypes";
import { findInteractionsAsSource } from "pbHelpers/Interaction";
import { describeMeasurement } from "pbHelpers/MeasurementDescriber";
import { pond } from "protobuf-ts/pond";
import { quack } from "protobuf-ts/quack";
//import { useGlobalState } from "providers";
import React, { useState } from "react";
//import { or } from "utils/types";
import UnitMeasurementSummary from "./UnitMeasurementSummary";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles((theme: Theme) => {
  return ({
    borderedContainer: {
      padding: theme.spacing(1),
      marginBottom: theme.spacing(2),
      border: "1px solid rgba(255, 255, 255, 0.12)",
      borderRadius: "4px"
    },
    container: {
      padding: theme.spacing(1),
      marginBottom: theme.spacing(2)
    },
    grainNode: {
      color: lightGreen[700]
    },
    airNode: {
      color: theme.palette.text.primary
    },
    divider: {
      margin: theme.spacing(1)
    },
    fullWidth: {
      width: "100%"
    }
  })
});

interface Props {
  deviceKey: string;
  componentKey: string;
  component: Component;
  interactions: Interaction[];
  sampling: boolean;
  //samples?: pond.Measurement[]; //deprecated: old measurement structure
  unitMeasurements?: UnitMeasurement[];
  sampleLimit?: number;
  updateDate?: (startDate: any, endDate: any, live?: boolean) => void;
  allowLive?: boolean;
  //recentMeasurement?: pond.Measurement;
  recentUnitMeasurement?: UnitMeasurement[];
  deviceComponentPreferences?: pond.DeviceComponentPreferences;
}

// function setComponentGraphRanges(device: number | string, component: string, ranges: Range[]) {
//   const key: string = "graphRanges-" + deviceComponentID(device, component);
//   localStorage.setItem(key, JSON.stringify(or(ranges, [])));
// }

// function getComponentGraphRanges(device: number | string, component: string): Range[] {
//   const key: string = "graphRanges-" + deviceComponentID(device, component);
//   return JSON.parse(or(localStorage.getItem(key), "[]"));
// }

export default function ComponentChart(props: Props) {
  //const { component, deviceComponentPreferences } = props;
  const classes = useStyles();
  const isMobile = useMobile();
  // const { deviceKey, componentKey } = props;
  // const prevDevice = usePrevious(props.deviceKey);
  // const prevComponentKey = usePrevious(props.componentKey);
  // const prevComponent = usePrevious(props.component);
  const defaultDateRange = GetDefaultDateRange();
  const [startDate, setStartDate] = useState(defaultDateRange.start);
  const [endDate, setEndDate] = useState(defaultDateRange.end);
  const [live, setLive] = useState(defaultDateRange.live);
  const [graphFilters, setGraphFilters] = useState<GraphFilters>({
    selectedNodes: ["all"],
    selectedInteractions: [],
    selectedOverlays: [],
    grainType: pond.Grain.GRAIN_NONE
  });
  // const [{ newStructure }] = useGlobalState();
  const [expandOverlays, setExpandOverlays] = useState(false);
  const [expandInteractions, setExpandInteractions] = useState(false);
  const [expandData, setExpandData] = useState(false);
  const [showOriginal, setShowOriginal] = useState(true);
  const [showAveraged, setShowAveraged] = useState(false);
  const [showAllNodes, setShowAllNodes] = useState(false);

  // useEffect(() => {
  //   if (prevComponent !== props.component) {
  //     let updatedFilters = cloneDeep(graphFilters);
  //     let filledTo = props.component.settings.grainFilledTo;
  //     updatedFilters.grainFilledTo = filledTo > 0 ? filledTo : undefined;
  //     updatedFilters.grainType = props.component.settings.grainType;
  //     setGraphFilters(updatedFilters);
  //   }
  // }, [prevComponent, graphFilters, props.component]);

  // useEffect(() => {
  //   if (prevDevice !== deviceKey || prevComponentKey !== componentKey) {
  //     const ranges = getComponentGraphRanges(deviceKey, componentKey);
  //     let updatedFilters = cloneDeep(graphFilters);
  //     updatedFilters.ranges = ranges;
  //     setGraphFilters(updatedFilters);
  //   }
  // }, [deviceKey, prevDevice, prevComponentKey, componentKey, graphFilters]);

  //use the excluded nodes to set the default for the graph filters
  // useEffect(() => {
  //   let excludedNodes = component.settings.excludedNodes;
  //   if (excludedNodes === undefined || excludedNodes.length === 0) return;
  //   let updatedFilters = cloneDeep(graphFilters);
  //   if (excludedNodes && component.lastMeasurement[0]) {
  //     let includedNodes: string[] = [];
  //     let numNodes = GetNumNodesFromUnitMeasurement(
  //       UnitMeasurement.any(component.lastMeasurement[0])
  //     );

  //     for (let i = 0; i < numNodes; i++) {
  //       if (!excludedNodes.includes(i)) {
  //         includedNodes.push(i.toString());
  //       }
  //     }
  //     updatedFilters.selectedNodes = includedNodes;
  //   }
  //   setGraphFilters(updatedFilters);
  // }, [component]); //eslint-disable-line react-hooks/exhaustive-deps

  const updateDateRange = (newStartDate: any, newEndDate: any, live: boolean) => {
    setStartDate(newStartDate);
    setEndDate(newEndDate);
    setLive(live);
    if (props.updateDate) {
      props.updateDate(newStartDate, newEndDate, live);
    }
  };

  // const changeRange = (index: number, range: Range) => {
  //   let updatedFilters = cloneDeep(graphFilters);
  //   let ranges = updatedFilters.ranges ? updatedFilters.ranges : [];
  //   ranges[index] = range;
  //   updatedFilters.ranges = ranges;
  //   setComponentGraphRanges(deviceKey, componentKey, ranges);
  //   setGraphFilters(updatedFilters);
  // };

  const handleGrainCableControlsChange = (name: string) => (event: any) => {
    let updatedFilters = cloneDeep(graphFilters);
    let selectedNodes = updatedFilters.selectedNodes ? updatedFilters.selectedNodes : ["all"];
    if (event.target.checked) {
      if (name === "all" || name === "grain" || name === "air") {
        selectedNodes = [name];
      } else {
        selectedNodes = selectedNodes.filter(item => {
          let str = item.toString();
          return str !== "all" && str !== "air" && str !== "grain";
        });
        selectedNodes.push(name);
      }
    } else {
      if (selectedNodes.includes(name)) {
        selectedNodes = selectedNodes.filter(item => item.toString() !== name.toString());
        if (selectedNodes.length < 1 && name !== "all") {
          selectedNodes = ["all"];
        }
      }
    }
    updatedFilters.selectedNodes = selectedNodes;
    setGraphFilters(updatedFilters);
  };

  const cableControls = () => {
    const { recentUnitMeasurement } = props;
    //const excludedNodes = component.settings.excludedNodes ?? [];
    const selectedNodes = graphFilters.selectedNodes ? graphFilters.selectedNodes : ["all"];
    let numNodes = 0;
    // if (samples) {
    //   numNodes = GetNumNodes(
    //     component.settings.type,
    //     recentUnitMeasurement
    //   );
    // } else {
      if (recentUnitMeasurement && recentUnitMeasurement.length > 0) {
        numNodes = GetNumNodesFromUnitMeasurement(
          recentUnitMeasurement[0]
        );
      }
    //}

    if (numNodes <= 1) {
      return null;
    }

    let grainCableControls = [];
    let split = isBinSplit(graphFilters);
    let splitAt = binSplitAt(graphFilters);

    for (var i = numNodes; i > 0; i--) {
      if (i === numNodes) {
        grainCableControls.push(
          <Grid size={{ xs: 12 }} key="group-selectors">
            <FormControlLabel
              control={
                <Checkbox
                  checked={selectedNodes.includes("all") ? true : false}
                  onChange={handleGrainCableControlsChange("all")}
                  value={"all"}
                  disabled={selectedNodes.includes("all") ? true : false}
                />
              }
              label={"All"}
            />
            {split && (
              <FormControlLabel
                control={
                  <Checkbox
                    checked={selectedNodes.includes("grain") ? true : false}
                    onChange={handleGrainCableControlsChange("grain")}
                    value={"grain"}
                    disabled={selectedNodes.includes("grain") ? true : false}
                  />
                }
                label={
                  // newStructure ? (
                    <Typography variant="body2" className={classes.grainNode}>
                      {graphFilters.grainType ? grainName(graphFilters.grainType) : "Grain"}
                    </Typography>
                  // ) : (
                  //   <Typography className={classes.grainNode}>
                  //     {graphFilters.grainType ? grainName(graphFilters.grainType) : "Grain"}
                  //   </Typography>
                  // )
                }
              />
            )}
            {split && (
              <FormControlLabel
                control={
                  <Checkbox
                    checked={selectedNodes.includes("air") ? true : false}
                    onChange={handleGrainCableControlsChange("air")}
                    value={"air"}
                    disabled={selectedNodes.includes("air") ? true : false}
                  />
                }
                label={<Typography variant="body2">Air</Typography>}
              />
            )}
            <Divider key="divider" />
          </Grid>
        );
      }

      let nodeLabel = "Node " + i.toString();
      if (i === 1) {
        nodeLabel = "Bottom";
      } else if (i === numNodes) {
        nodeLabel = "Top";
      }

      //TODO-DRAGER: this mey not be necessary to do anymore with them being split up
      // if (component.type() === quack.ComponentType.COMPONENT_TYPE_DRAGER_GAS_DONGLE) {
      //   let describer = describeMeasurement(
      //     component.lastMeasurement[0].type,
      //     component.type(),
      //     component.subType()
      //   );
      //   let details = describer.nodeDetails();
      //   if (details) {
      //     nodeLabel = details.labels[i - 1];
      //   }
      // }

      grainCableControls.push(
        <Grid size={{ xs: 6 }} key={"node-" + (i - 1).toString()}>
          <FormControlLabel
            className={split && i <= splitAt ? classes.grainNode : classes.airNode}
            control={
              <Checkbox
                checked={selectedNodes.includes((i - 1).toString()) ? true : false}
                onChange={handleGrainCableControlsChange((i - 1).toString())}
                value={(i - 1).toString()}
                //disabled={excludedNodes.includes(i - 1)}
              />
            }
            label={<Typography variant="body2">{nodeLabel}</Typography>}
          />
        </Grid>
      );
    }
    return numNodes > 0 ? (
      <Card raised style={{ padding: 25, marginBottom: 20 }}>
        <Typography variant="body2" style={{ fontWeight: 650 }}>
          Node Control
        </Typography>
        <FormGroup>
          <Grid container direction="row">
            {grainCableControls}
          </Grid>
        </FormGroup>
      </Card>
    ) : null;
  };

  const componentTypeControls = () => {
    const { component } = props;
    const ext = extension(component.settings.type, component.settings.subtype);
    if (ext.isArray) {
      return cableControls();
    }
    return null;
  };

  const updateInteractions = (i: Interaction) => {
    let updatedFilters = cloneDeep(graphFilters);
    let selectedInteractions = updatedFilters.selectedInteractions
      ? updatedFilters.selectedInteractions
      : [];
    if (selectedInteractions.includes(i.key())) {
      selectedInteractions.splice(selectedInteractions.indexOf(i.key()), 1);
    } else {
      selectedInteractions.push(i.key());
    }
    updatedFilters.selectedInteractions = selectedInteractions;
    setGraphFilters(updatedFilters);
  };

  const interactionControls = () => {
    const { component, interactions } = props;
    let componentID: quack.ComponentID = quack.ComponentID.fromObject({
      address: component.settings.address,
      addressType: component.settings.addressType,
      type: component.settings.type
    });
    let sourceInteractions = findInteractionsAsSource(componentID, interactions);
    const selectedInteractions = graphFilters.selectedInteractions
      ? graphFilters.selectedInteractions
      : [];

    //create checkboxes for each interaction and as they are checked/unchecked add/remove them from the interactions passed to getComponentVisual
    return interactions.length > 0 ? (
      <Card raised className={classes.container}>
        <Accordion
          elevation={0}
          expanded={expandInteractions}
          onChange={(_, expanded) => {
            setExpandInteractions(expanded);
          }}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography variant="body2" style={{ fontWeight: 650 }}>
              Interactions
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container>
              {sourceInteractions.map((interaction, i) => (
                <Grid size={{ xs: 12 }} key={"interaction " + i}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={selectedInteractions.includes(interaction.key())}
                        onChange={() => updateInteractions(interaction)}
                        value={interaction}
                      />
                    }
                    label={<Typography variant="body2">Interaction {i + 1}</Typography>}
                  />
                </Grid>
              ))}
            </Grid>
          </AccordionDetails>
        </Accordion>
      </Card>
    ) : null;

    // return interactions.length > 0 ? (
    //   <FormControl className={classes.borderedContainer}>
    //     <FormLabel component="legend">Interactions</FormLabel>
    //     <FormGroup>
    //       <Grid container direction="column">
    //         {sourceInteractions.map((interaction, i) => (
    //           <Grid item xs={12} key={"interaction " + i}>
    //             <FormControlLabel
    //               control={
    //                 <Checkbox
    //                   checked={selectedInteractions.includes(interaction.key())}
    //                   onChange={() => updateInteractions(interaction)}
    //                   value={interaction}
    //                 />
    //               }
    //               label={"Interaction " + (i + 1)}
    //             />
    //           </Grid>
    //         ))}
    //       </Grid>
    //     </FormGroup>
    //   </FormControl>
    // ) : null;
  };

  const updateOverlays = (overlayIndex: number) => {
    let updatedFilters = cloneDeep(graphFilters);
    // let selectedInteractions = updatedFilters.selectedInteractions
    //   ? updatedFilters.selectedInteractions
    //   : [];
    let selectedOverlays = updatedFilters.selectedOverlays ?? [];
    if (selectedOverlays.includes(overlayIndex.toString())) {
      selectedOverlays.splice(selectedOverlays.indexOf(overlayIndex.toString()), 1);
    } else {
      selectedOverlays.push(overlayIndex.toString());
    }
    updatedFilters.selectedOverlays = selectedOverlays;
    setGraphFilters(updatedFilters);
  };

  const overlayControls = () => {
    const { component } = props;
    // let componentID: quack.ComponentID = quack.ComponentID.fromObject({
    //   address: component.settings.address,
    //   addressType: component.settings.addressType,
    //   type: component.settings.type
    // });
    let overlays = component.settings.overlays;
    if (overlays.length === 0) return;
    const selectedOverlays = graphFilters.selectedOverlays ?? [];
    // if (newStructure) {
      return overlays.length > 0 ? (
        <Card raised className={classes.container}>
          <Accordion
            elevation={0}
            expanded={expandOverlays}
            onChange={(_, expanded) => {
              setExpandOverlays(expanded);
            }}>
            <AccordionSummary expandIcon={<ExpandMore />}>
              <Typography variant="body2" style={{ fontWeight: 650 }}>
                Overlays
              </Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Grid container>
                {overlays.map((overlay, i) => (
                  <Grid size={{ xs: 12 }} key={"overlay:" + i}>
                    <FormControl fullWidth>
                      <FormControlLabel
                        classes={{
                          label: classes.fullWidth
                        }}
                        control={
                          <Checkbox
                            checked={selectedOverlays.includes(i.toString())}
                            onChange={() => updateOverlays(i)}
                            value={overlay.message}
                          />
                        }
                        label={
                          <Grid container direction="row" justifyContent="space-between">
                            <Grid >
                              <Typography variant="body2">{overlay.message}</Typography>
                            </Grid>
                            <Grid>
                              <Box
                                width="20px"
                                height="20px"
                                borderRadius="50%"
                                //className={classes.on}
                                style={{ background: overlay.colour }}
                              />
                            </Grid>
                          </Grid>
                        }
                      />
                    </FormControl>
                  </Grid>
                ))}
              </Grid>
            </AccordionDetails>
          </Accordion>
        </Card>
      ) : null;
    // }
    // return overlays.length > 0 ? (
    //   <FormControl className={classes.borderedContainer}>
    //     <FormLabel component="legend">Overlays</FormLabel>
    //     <FormGroup>
    //       <Grid container direction="column">
    //         {overlays.map((overlay, i) => (
    //           <Grid item xs={12} key={"overlay:" + i}>
    //             <FormControlLabel
    //               control={
    //                 <Checkbox
    //                   checked={selectedOverlays.includes(i.toString())}
    //                   onChange={() => updateOverlays(i)}
    //                   value={overlay.message}
    //                 />
    //               }
    //               label={overlay.message}
    //             />
    //           </Grid>
    //         ))}
    //       </Grid>
    //     </FormGroup>
    //   </FormControl>
    // ) : null;
  };

  const dataDisplayControls = () => {
    const { unitMeasurements } = props;
    return (
      <Card raised className={classes.container}>
        <Accordion
          elevation={0}
          expanded={expandData}
          onChange={(_, expanded) => {
            setExpandData(expanded);
          }}>
          <AccordionSummary expandIcon={<ExpandMore />}>
            <Typography variant="body2" style={{ fontWeight: 650 }}>
              Data Display Options
            </Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Grid container style={{ width: "100%" }}>
              <Grid size={{ xs: 12 }}>
                <FormControl fullWidth>
                  <FormControlLabel
                    classes={{
                      label: classes.fullWidth
                    }}
                    control={
                      <Checkbox
                        checked={showOriginal}
                        onChange={(_, checked) => {
                          setShowOriginal(checked);
                        }}
                        value={showOriginal}
                      />
                    }
                    label={
                      <Grid container direction="row" justifyContent="space-between" wrap="nowrap">
                        <Grid >
                          <Typography variant="body2">OriginalData</Typography>
                        </Grid>
                        <Grid >
                          <Grid container spacing={1}>
                            {unitMeasurements?.map((um, i) => (
                              <Grid key={i}>
                                <Box
                                  width="20px"
                                  height="20px"
                                  borderRadius="50%"
                                  //className={classes.on}
                                  style={{ background: describeMeasurement(um.type).colour() }}
                                />
                              </Grid>
                            ))}
                          </Grid>
                        </Grid>
                      </Grid>
                    }
                  />
                </FormControl>
              </Grid>
              <Grid size={{ xs: 12 }}>
                <FormControl fullWidth>
                  <FormControlLabel
                    classes={{
                      label: classes.fullWidth
                    }}
                    control={
                      <Checkbox
                        checked={showAveraged}
                        onChange={(_, checked) => {
                          setShowAveraged(checked);
                        }}
                        value={showAveraged}
                      />
                    }
                    label={
                      <Grid container direction="row" justifyContent="space-between">
                        <Grid >
                          <Typography variant="body2">Averaged Data</Typography>
                        </Grid>
                        <Grid >
                          <Box
                            width="20px"
                            height="20px"
                            borderRadius="50%"
                            //className={classes.on}
                            style={{ background: "white" }}
                          />
                        </Grid>
                      </Grid>
                    }
                  />
                </FormControl>
              </Grid>
            </Grid>
          </AccordionDetails>
        </Accordion>
      </Card>
    );
  };

  const getGraph = () => {
    const { component, interactions, unitMeasurements, sampleLimit } = props;
    // if (samples && samples.length > 1) {
    //   //TODO: is being deprecated
    //   return getComponentVisual(
    //     component.settings.type,
    //     component.settings.subtype,
    //     samples,
    //     interactions,
    //     component.settings.overlays,
    //     GraphOrientation.GRAPH_ORIENTATION_LANDSCAPE,
    //     graphFilters
    //   );
    // } else
    if (unitMeasurements) {
      return (
        <React.Fragment>
          <MeasurementsChart
            startDate={startDate}
            endDate={endDate}
            component={component}
            interactions={interactions}
            unitMeasurements={unitMeasurements}
            sampleLimit={sampleLimit}
            filters={graphFilters}
            updateDateRange={updateDateRange}
            showOriginal={showOriginal}
            showAveraged={showAveraged}
          />
        </React.Fragment>
      );
    } else {
      return (
        <React.Fragment>
          <Typography variant="h6" color="textPrimary" align="center">
            Not enough data to display
          </Typography>
          <Typography variant="subtitle2" color="textSecondary" align="center">
            {live
              ? "(Waiting to receive a few live measurements)"
              : "(Queried between " +
                moment(startDate).calendar() +
                " and " +
                moment(endDate).calendar() +
                ")"}
          </Typography>
        </React.Fragment>
      );
    }
  };

  const displayExcludedNodes = () => {
    const {component} = props
    let nodes: number[] = []
    component.settings.excludedNodes.forEach(node => {
      nodes.push(node+1)
    })
    return nodes
  }

  const content = () => {
    const {
      component,
      sampling,
      recentUnitMeasurement
    } = props;
    //const ext = extension(component.settings.type, component.settings.subtype);
    //const ranges = graphFilters.ranges ? graphFilters.ranges : [];
    let convertedLastMeasurement;

    //console.log(recentUnitMeasurement)

    if (recentUnitMeasurement && recentUnitMeasurement.length > 0) {
      let measurements = recentUnitMeasurement;
      convertedLastMeasurement = UnitMeasurement.convertLastMeasurement(measurements);
    }
    return (
      <Grid container spacing={2} direction={isMobile ? "column" : "row-reverse"}>
        {isMobile && (
          <Grid className={classes.borderedContainer}>
            {/* {samples ? (
              <MeasurementSummary component={component} reading={recentMeasurement} />
            ) : ( */}
              <Card raised className={classes.container}>
                <Typography style={{ fontWeight: 650 }}>Latest Measurements:</Typography>
                <UnitMeasurementSummary
                  component={component}
                  reading={convertedLastMeasurement}
                />
              </Card>
            {/* )} */}
          </Grid>
        )}
        <Grid
          size={{
            xs: 12,
            sm: 7,
            md: 8,
            lg: 9,
            xl: 10
          }}
          container
          direction="column"
          justifyContent="center"
          alignItems="center">
          {sampling ? <CircularProgress /> : <React.Fragment>{getGraph()}</React.Fragment>}
        </Grid>
        <Grid size={{ xs: 12, sm: 5, md: 4, lg: 3, xl: 2 }} container alignContent="flex-start">
          {!isMobile && (
            <React.Fragment>
              {/* {newStructure && ( */}
                <Grid size={{ xs: 12 }}>
                  <Box display="flex" justifyContent="space-between">
                    <Box>
                      <Typography style={{ fontWeight: 650, fontSize: 20 }}>Status</Typography>
                    </Box>
                    {component.settings.excludedNodes.length > 0 &&
                      <Box display="flex" alignContent="center" margin="auto" marginX={0}>
                        <Typography textAlign="center" marginX={1}>
                          Excluded Nodes 
                        </Typography>
                        <Tooltip
                          title={"You have excluded nodes (" + displayExcludedNodes().toLocaleString() + ") and they will not show up on this page, you can reveal them temporarily by selecting show errors"}>
                          <Warning color="warning"/>
                        </Tooltip>
                      </Box>
                    }
                  </Box>
                  <Divider variant="middle" className={classes.divider} />
                </Grid>
              {/* )} */}
              <Grid size={{ xs: 12 }} className={classes.borderedContainer}>
                {/* {samples ? (
                  <MeasurementSummary component={component} reading={recentMeasurement} />
                ) : ( */}
                  <Card raised style={{ padding: 25, marginBottom: 20 }}>
                    <Typography style={{ fontWeight: 650 }}>Latest Measurements:</Typography>
                    <UnitMeasurementSummary
                      component={component}
                      reading={convertedLastMeasurement}
                      largeText
                      boldMeasurements
                    />
                  </Card>
                {/* )} */}
              </Grid>
            </React.Fragment>
          )}
          {!isMobile && (
            <Grid size={{ xs: 12 }}>
              <Typography style={{ fontWeight: 650, fontSize: 20 }}>Graph Controls</Typography>
              <Divider variant="middle" className={classes.divider} />
            </Grid>
          )}
          <Grid size={{ xs: 12 }}>
            {componentTypeControls()}
          </Grid>
          <Grid size={{ xs: 12 }}>
            {interactionControls()}
          </Grid>
          <Grid size={{ xs: 12 }}>
            {overlayControls()}
          </Grid>
          {component.settings.smoothingAverages !== 0 && (
            <Grid size={{ xs: 12 }}>
              {dataDisplayControls()}
            </Grid>
          )}

          {/* {!sampling &&
            ext.measurements.map((m, i) => {
              const range = ranges[i] ? ranges[i] : ({} as Range);
              if (m.measurementType === quack.MeasurementType.MEASUREMENT_TYPE_BOOLEAN) {
                return null;
              }
              if (samples) {
                return (
                  <Grid size={{ xs: 12 }} key={"range-" + i}>
                    <RangeInput
                      range={range}
                      onChange={(updatedRange: Range) => changeRange(i, updatedRange)}
                      label={m.label + " Range"}
                    />
                  </Grid>
                );
              }
              return null;
            })} */}
        </Grid>
      </Grid>
    );
  };

  return (
    <Card>
      <CardContent>{content()}</CardContent>
    </Card>
  );
}
