import React from "react";
import { EnergyApi } from "../../api/EnergyApi";
import { useSnackbar } from "../../hooks/context_providers/SnackbarProvider";
import StatCard from "../../widgets/StatCard";

export function CachedConsumptionWidget(): React.ReactElement {
  const snackbar = useSnackbar();

  const [val, setVal] = React.useState<undefined | number>();

  const refresh = async () => {
    try {
      const s = await EnergyApi.CachedConsumption();
      setVal(s);
    } catch (e) {
      console.error(e);
      snackbar("Failed to refresh cached consumption!");
    }
  };

  React.useEffect(() => {
    refresh();
    const i = setInterval(() => refresh(), 3000);

    return () => clearInterval(i);
  });

  return (
    <StatCard title="Cached consumption" value={val?.toString() ?? "Loading"} />
  );
}
