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

export function useTaskCount() {
  const [taskCount, setTaskCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const { user } = useAuth();

  const fetchTaskCount = async () => {
    if (!user) return;
    
    try {
      const { count: workflowCount, error: workflowError } = await supabase
        .from('tasks')
        .select('id', { count: 'exact', head: true })
        .is('parent_task_id', null)
        .not('template_id', 'is', null)
        .eq('status', 'pending');

      if (workflowError) throw workflowError;

      const { count: standaloneCount, error: standaloneError } = await supabase
        .from('tasks')
        .select('id', { count: 'exact', head: true })
        .is('parent_task_id', null)
        .is('template_id', null)
        .eq('status', 'pending');

      if (standaloneError) throw standaloneError;

      const total = (workflowCount || 0) + (standaloneCount || 0);
      setTaskCount(total);
    } catch (err) {
      console.error('Error fetching task count:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTaskCount();

    const channel = supabase
      .channel('public:tasks_count')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'tasks' }, () => {
        fetchTaskCount();
      })
      .subscribe();

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

  return { taskCount, loading, refreshCount: fetchTaskCount };
}
