import { useEffect } from "react";

export default function useAppPolling({
  activeTab,
  selectedTaskId,
  isVisible,
  setIsVisible,
  setNow,
  tasksPollInFlight,
  accountsPollInFlight,
  logsPollInFlight,
  eventsPollInFlight,
  setTasks,
  loadTaskStatuses,
  setTaskStatus,
  setAccounts,
  setAccountAssignments,
  setAccountStats,
  setGlobalStatus,
  setLogs,
  setInvites,
  setFallbackList,
  setConfirmQueue,
  setTaskAudit,
  setAccountEvents,
  setQueueItems,
  setQueueStats
}) {
  useEffect(() => {
    if (!window.api) return undefined;
    const load = async () => {
      if (!isVisible || tasksPollInFlight.current) return;
      tasksPollInFlight.current = true;
      try {
        const tasksData = await window.api.listTasks();
        setTasks(tasksData);
        await loadTaskStatuses(tasksData);
        if (selectedTaskId != null) {
          setTaskStatus(await window.api.taskStatus(selectedTaskId));
        }
      } finally {
        tasksPollInFlight.current = false;
      }
    };
    load();
    const interval = setInterval(async () => {
      await load();
    }, 5000);
    return () => clearInterval(interval);
  }, [selectedTaskId, isVisible]);

  useEffect(() => {
    if (!window.api) return undefined;
    const load = async () => {
      if (!isVisible || accountsPollInFlight.current) return;
      accountsPollInFlight.current = true;
      try {
        setAccounts(await window.api.listAccounts());
        setAccountAssignments(await window.api.listAccountAssignments());
        const statusData = await window.api.getStatus();
        setAccountStats(statusData.accountStats || []);
        setGlobalStatus({
          connectedSessions: statusData.connectedSessions || 0,
          totalAccounts: statusData.totalAccounts || 0
        });
      } finally {
        accountsPollInFlight.current = false;
      }
    };
    load();
    const interval = setInterval(load, 15000);
    return () => clearInterval(interval);
  }, [isVisible]);

  useEffect(() => {
    if (!window.api || (activeTab !== "logs" && activeTab !== "queue") || selectedTaskId == null) return undefined;
    const load = async () => {
      if (!isVisible || logsPollInFlight.current) return;
      logsPollInFlight.current = true;
      try {
        setLogs(await window.api.listLogs({ limit: 100, taskId: selectedTaskId }));
        setInvites(await window.api.listInvites({ limit: 200, taskId: selectedTaskId }));
        setFallbackList(await window.api.listFallback({ limit: 500, taskId: selectedTaskId }));
        setConfirmQueue(await window.api.listConfirmQueue({ limit: 500, taskId: selectedTaskId }));
        setTaskAudit(await window.api.listTaskAudit(selectedTaskId));
        const queueData = await window.api.listQueue({ limit: 200, taskId: selectedTaskId });
        if (queueData && queueData.items) setQueueItems(queueData.items);
        if (queueData && queueData.stats) setQueueStats(queueData.stats);
      } finally {
        logsPollInFlight.current = false;
      }
    };
    load();
    const interval = setInterval(load, 5000);
    return () => clearInterval(interval);
  }, [activeTab, selectedTaskId, isVisible]);

  useEffect(() => {
    if (!window.api || activeTab !== "events") return undefined;
    const load = async () => {
      if (!isVisible || eventsPollInFlight.current) return;
      eventsPollInFlight.current = true;
      try {
        setAccountEvents(await window.api.listAccountEvents(200));
      } finally {
        eventsPollInFlight.current = false;
      }
    };
    load();
    const interval = setInterval(load, 10000);
    return () => clearInterval(interval);
  }, [activeTab, isVisible]);

  useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(timer);
  }, [setNow]);

  useEffect(() => {
    const handleVisibility = () => {
      setIsVisible(!document.hidden);
    };
    document.addEventListener("visibilitychange", handleVisibility);
    window.addEventListener("focus", handleVisibility);
    window.addEventListener("blur", handleVisibility);
    return () => {
      document.removeEventListener("visibilitychange", handleVisibility);
      window.removeEventListener("focus", handleVisibility);
      window.removeEventListener("blur", handleVisibility);
    };
  }, [setIsVisible]);
}
