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

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

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

  const refresh = async () => {
    try {
      const s = await EnergyApi.RelaysConsumption();
      const history = await EnergyApi.RelaysConsumptionHistory();
      setVal(s);
      setHistory(history);
    } catch (e) {
      console.error(e);
      snackbar("Failed to refresh current relays consumption!");
    }
  };

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

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

  return (
    <StatCard
      title="Relays consumption"
      data={history ?? []}
      interval="Last day"
      value={val?.toString() ?? "Loading"}
    />
  );
}
