import React from "react";
import { InboxApi } from "../api/InboxApi";
import { AsyncWidget } from "../widgets/AsyncWidget";

interface UnmatchedInboxEntriesCountContext {
  count: number;
  reload: () => Promise<void>;
}

const UnmatchedInboxEntriesCountContextK =
  React.createContext<UnmatchedInboxEntriesCountContext | null>(null);

export function UnmatchedInboxEntriesCountProvider(
  p: React.PropsWithChildren
): React.ReactElement {
  const [count, setCount] = React.useState<number | null>(null);

  const loadKey = React.useRef(1);

  const loadPromise = React.useRef<(() => void) | null>(null);

  const load = async () => {
    setCount(await InboxApi.CountUnmatched());
  };

  const onReload = async () => {
    load();

    return new Promise<void>((res) => {
      loadPromise.current = () => {
        res();
      };
    });
  };

  return (
    <AsyncWidget
      ready={true}
      loadKey={loadKey.current}
      load={load}
      errMsg="Failed to get the number of unread inbox entries!"
      build={() => {
        if (loadPromise.current != null) {
          loadPromise.current();
          loadPromise.current = null;
        }

        return (
          <UnmatchedInboxEntriesCountContextK
            value={{
              count: count ?? 0,
              reload: onReload,
            }}
          >
            {p.children}
          </UnmatchedInboxEntriesCountContextK>
        );
      }}
    />
  );
}

export function useUnmatchedInboxEntriesCount(): UnmatchedInboxEntriesCountContext {
  return React.use(UnmatchedInboxEntriesCountContextK)!;
}
