'use client';

import { useEffect, useRef, useState, useCallback } from 'react';

interface UsePollingOptions {
  intervalMs?: number;
  enabled?: boolean;
  runOnMount?: boolean;
}

interface UsePollingResult {
  lastUpdated: Date | null;
  trigger: () => void;
}

export function usePolling(
  callback: () => Promise<void> | void,
  { intervalMs = 30000, enabled = true, runOnMount = true }: UsePollingOptions = {},
): UsePollingResult {
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const savedCallback = useRef(callback);
  const isRunning = useRef(false);
  const mountedRef = useRef(true);

  useEffect(() => { savedCallback.current = callback; }, [callback]);

  useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []);

  const execute = useCallback(async () => {
    if (isRunning.current || !mountedRef.current) return;
    isRunning.current = true;
    try {
      await savedCallback.current();
      if (mountedRef.current) setLastUpdated(new Date());
    } finally {
      isRunning.current = false;
    }
  }, []);

  useEffect(() => {
    if (!enabled) return;

    if (runOnMount) {
      execute();
    }

    const interval = setInterval(() => {
      if (!document.hidden) execute();
    }, intervalMs);

    const handleVisibilityChange = () => {
      if (!document.hidden) execute();
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      clearInterval(interval);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [enabled, intervalMs, execute, runOnMount]);

  return { lastUpdated, trigger: execute };
}

export function formatLastUpdated(date: Date | null): string {
  if (!date) return '';
  const diffSec = Math.floor((Date.now() - date.getTime()) / 1000);
  if (diffSec < 10) return 'just now';
  if (diffSec < 60) return `${diffSec}s ago`;
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
