import React, { useEffect, useState } from "react";
import { Button, Grid, Link, Paper } from "@material-ui/core";
import CreateIcon from "@material-ui/icons/Create";

import api from "../../../services/grafanaAPI";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import ResponsiveIFrame from "../../Controls/ResponsiveIFrame";
import { logger } from "../../../services/monitoring";

const Datascope = () => {
  const classes = useStyles();
  const { setTitle, setSitePath } = useStatusContext();
  const REQUEST_INTERVAL = 10000;

  useEffect(() => {
    setTitle("Datascope");
    setSitePath([]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [carsCount, setCarsCount] = useState(0);
  useEffect(() => {
    api
      .getCarsCount()
      .then((result) => setCarsCount(result))
      .catch((error) => logger.warn(error.stack));
  }, []);

  const [signalsCount, setSignalsCount] = useState("0");
  useEffect(() => {
    storeSignals();

    const id = setInterval(function () {
      storeSignals();
    }, REQUEST_INTERVAL);
    return () => {
      clearInterval(id);
    };
  }, []);

  const storeSignals = () => {
    api
      .getSignalsCount()
      .then((result) => {
        let num = result.toLocaleString();
        setSignalsCount(num);
      })
      .catch((error) => logger.warn(error.stack));
  };

  return (
    <div className={classes.paper}>
      <Grid container className={classes.root} spacing={2}>
        <Grid item md={6}>
          <Paper className={classes.grafanaContainer} style={{ height: 150 }}>
            <h1 className={classes.datascopeContainerValue}>{carsCount}</h1>
            <h2 className={classes.datascopeContainerText}>Cars</h2>
          </Paper>
        </Grid>

        <Grid item md={6}>
          <Paper className={classes.grafanaContainer} style={{ height: 150 }}>
            <h1 className={classes.datascopeContainerValue}>{signalsCount}</h1>
            <h2 className={classes.datascopeContainerText}>
              Signals Collected
            </h2>
          </Paper>
        </Grid>

        <Grid item md={12}>
          <Paper className={classes.grafanaContainer}>
            <ResponsiveIFrame
              classes={classes}
              src="https://grafana.fiskerdps.com/d-solo/1VTVJ_qGk/dashboard?orgId=2&refresh=30s&panelId=12"
              title="Signals Time Series"
            />
          </Paper>
        </Grid>
      </Grid>
      <Button
        style={{ marginTop: 10 }}
        aria-label="create"
        color="primary"
        component={Link}
        href="https://grafana.fiskerdps.com"
        rel="noopener"
        target="_blank"
      >
        <CreateIcon fontSize="large" />
        Go to Grafana
      </Button>
    </div>
  );
};

export default Datascope;
