import { Chip, Theme, Tooltip } from "@mui/material";
import { Schedule } from "@mui/icons-material";
import moment from "moment";
import { useEffect, useState } from "react";
import { makeStyles } from "@mui/styles";
import { yellow } from "@mui/material/colors";

const useStyles = makeStyles((theme: Theme) => {
  return ({
    notReporting: {
      color: theme.palette.text.secondary
    },
    reporting: {
      color: yellow["900"]
    }
  })
});

interface Props {
  lastMeasurement: string;
  periodMs: number;
  size?: "small" | "medium";
}

export function NextMeasurementChip(props: Props) {
  const { lastMeasurement, periodMs, size } = props;
  const classes = useStyles();
  const [countdown, setCountdown] = useState(0);

  useEffect(() => {
    let timer = setInterval(() => {
      if (countdown > 0) {
        setCountdown(countdown - 1);
      } else {
        const now = moment();
        let last = moment(lastMeasurement !== "" ? lastMeasurement : 0);
        let diff = now.diff(last, "seconds");
        const periodS = periodMs / 1000.0;
        let rem = periodS - diff;
        if (rem < 0) rem = 0;
        setCountdown(rem);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [countdown, lastMeasurement, periodMs]);

  const getTooltip = () => {
    let tooltip = "Not reporting measurements";
    if (periodMs > 0) {
      if (periodMs < 60000) {
        tooltip =
          "Reports a measurement every " + moment.duration(periodMs, "ms").asSeconds() + " seconds";
      } else {
        tooltip =
          "Reports a measurement every " +
          moment
            .duration(periodMs, "ms")
            .humanize()
            .replace("an ", "");
      }
    }
    return tooltip;
  };

  const getLabel = () => {
    let label = "Not reporting";
    if (periodMs > 0) {
      if (countdown < 5) {
        label = "Measuring soon";
      } else if (countdown <= 60) {
        label = "Measuring in a minute";
      } else {
        label =
          "Measuring " +
          moment()
            .utc()
            .to(moment.utc().add(countdown, "s"));
      }
    }
    return label;
  };

  return (
    <Tooltip title={getTooltip()}>
      <Chip
        variant="outlined"
        label={getLabel()}
        icon={<Schedule className={periodMs > 0 ? classes.reporting : classes.notReporting} />}
        size={size}
      />
    </Tooltip>
  );
}
