import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function useActiveWorkflowCount(clientId = null) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const fetchCount = async () => {
      try {
        let query = supabase
          .from('tasks')
          .select('*', { count: 'exact', head: true })
          .not('template_id', 'is', null)
          .is('parent_task_id', null)
          .neq('status', 'completed');

        if (clientId) {
          query = query.eq('client_id', clientId);
        }

        const { count: c, error } = await query;
        
        if (error) {
          console.error('Error fetching workflow count:', error);
          return;
        }
        
        setCount(c || 0);
      } catch (err) {
        console.error('Unexpected error in useActiveWorkflowCount:', err);
      }
    };

    fetchCount();

    const channel = supabase
      .channel(`active_workflows_count_${clientId || 'admin'}`)
      .on(
        'postgres_changes',
        { event: '*', schema: 'public', table: 'tasks' },
        () => {
          fetchCount();
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  }, [clientId]);

  return count;
}
