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

export function CurrConsumptionWidget(): 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.GridConsumption();
      const history = await EnergyApi.GridConsumptionHistory();
      setVal(s);
      setHistory(history);
    } catch (e) {
      console.error(e);
      snackbar("Failed to refresh current consumption!");
    }
  };

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

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

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