import { useCallback, useEffect, useReducer } from "react";
import { loadAccountUsage, useAccountResetCredit } from "./status-api.js";
import { initialUsageStatus, reduceUsageStatus } from "./status-state.js";

export function useStatus(accountId) {
  const [state, dispatch] = useReducer(reduceUsageStatus, initialUsageStatus);
  const load = useCallback(async ({ silent = false } = {}) => {
    if (!accountId) return null;
    dispatch({ type: "loading", silent });
    try {
      const usage = await loadAccountUsage(accountId);
      dispatch({ type: "loaded", usage });
      return usage;
    } catch (error) {
      dispatch({ type: "failed", error: usageLoadError(error) });
      throw error;
    }
  }, [accountId]);
  useEffect(() => {
    if (!accountId) { dispatch({ type: "reset" }); return; }
    let active = true;
    dispatch({ type: "reset" });
    dispatch({ type: "loading" });
    const load = () => loadAccountUsage(accountId)
      .then((usage) => { if (active) dispatch({ type: "loaded", usage }); })
      .catch((error) => { if (active) dispatch({ type: "failed", error: usageLoadError(error) }); });
    load();
    const timer = setInterval(load, 60000);
    return () => { active = false; clearInterval(timer); };
  }, [accountId]);
  async function useResetCredit() {
    if (!accountId || state.resetPending) return null;
    dispatch({ type: "reset_credit_pending" });
    try {
      const result = await useAccountResetCredit(accountId);
      if (!["reset", "alreadyRedeemed"].includes(result.outcome)) {
        dispatch({ type: "reset_credit_failed", error: result.outcome });
        return result;
      }
      await load();
      dispatch({ type: "reset_credit_complete" });
      return result;
    } catch (error) {
      dispatch({ type: "reset_credit_failed", error: "reset_credit_unavailable" });
      throw error;
    }
  }
  return { ...state, reload: load, useResetCredit };
}

function usageLoadError(error) {
  return error?.message === "pc_unreachable" ? "pc_unreachable" : "";
}
