"use client";

import { fetchMasterDataIssuesSummaryClient } from "@/app/api/masterDataIssues/client";
import { useCallback, useEffect, useRef, useState } from "react";

const POLL_MS = 120_000;

export function useMasterDataIssueNavCount(enabled: boolean) {
  const [bomGroupCount, setBomGroupCount] = useState(0);
  const [itemGroupCount, setItemGroupCount] = useState(0);
  const [totalGroupCount, setTotalGroupCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const inFlightRef = useRef(false);

  const load = useCallback(async () => {
    if (!enabled) {
      setBomGroupCount(0);
      setItemGroupCount(0);
      setTotalGroupCount(0);
      return;
    }
    if (inFlightRef.current) return;
    inFlightRef.current = true;
    setLoading(true);
    try {
      const data = await fetchMasterDataIssuesSummaryClient();
      const bom = Number(data.bomGroupCount ?? 0);
      const item = Number(data.itemGroupCount ?? 0);
      const total = Number(data.totalGroupCount ?? bom + item);
      setBomGroupCount(Number.isFinite(bom) && bom > 0 ? bom : 0);
      setItemGroupCount(Number.isFinite(item) && item > 0 ? item : 0);
      setTotalGroupCount(Number.isFinite(total) && total > 0 ? total : 0);
    } catch {
      setBomGroupCount(0);
      setItemGroupCount(0);
      setTotalGroupCount(0);
    } finally {
      setLoading(false);
      inFlightRef.current = false;
    }
  }, [enabled]);

  useEffect(() => {
    if (!enabled) {
      setBomGroupCount(0);
      setItemGroupCount(0);
      setTotalGroupCount(0);
      return;
    }
    void load();
    const id = window.setInterval(() => void load(), POLL_MS);
    return () => window.clearInterval(id);
  }, [enabled, load]);

  return { bomGroupCount, itemGroupCount, totalGroupCount, loading, reload: load };
}
