import { useState, useEffect } from 'react';
import { getSLAStatus, SLAStatus } from '@/utils/slaTracker';

/**
 * Custom hook for real-time SLA tracking with working hours
 * Automatically updates every minute and pauses during non-working hours
 * 
 * @param startDate - When the SLA tracking started
 * @param deadline - When the SLA should complete
 * @param priority - Priority type ('express' = calendar hours, 'standard' = working hours)
 * @param enabled - Whether tracking is enabled (default: true)
 * @returns SLAStatus object with real-time updates
 */
export function useSLATracking(
  startDate: string | Date | null | undefined,
  deadline: string | Date | null | undefined,
  priority?: string,
  enabled: boolean = true
): SLAStatus | null {
  const [slaStatus, setSlaStatus] = useState<SLAStatus | null>(null);

  useEffect(() => {
    if (!enabled || !startDate || !deadline) {
      setSlaStatus(null);
      return;
    }

    // Initial calculation
    const updateStatus = () => {
      try {
        const status = getSLAStatus(startDate, deadline, priority);
        setSlaStatus(status);
      } catch (error) {
        console.error('[useSLATracking] Error calculating SLA status:', error);
      }
    };

    updateStatus();

    // Update every minute
    const interval = setInterval(updateStatus, 60000); // 60 seconds

    return () => clearInterval(interval);
  }, [startDate, deadline, priority, enabled]);

  return slaStatus;
}

