import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { COLLECTION_UPDATE_EVENT } from '@/hooks/useCollectionSync';

export function useCollectionStageAdvance() {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const advanceStage = useCallback(async (collection, onSuccess) => {
    if (!collection) {
      console.error("No collection provided to advanceStage");
      return { success: false, error: "No collection data provided" };
    }

    setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const today = new Date().toISOString();

      const updates = {
        status: collection.status === 'open' ? 'in_progress' : 'resolved',
        notes: `${collection.notes || ''}\nStage advanced on ${today} by ${user?.email || 'system'}`.trim(),
        updated_at: today
      };

      const { data, error } = await supabase
        .from('collections')
        .update(updates)
        .eq('id', collection.id)
        .select()
        .single();

      if (error) throw error;

      window.dispatchEvent(new CustomEvent(COLLECTION_UPDATE_EVENT, { 
        detail: { type: 'STAGE_ADVANCE', id: collection.id, data }
      }));

      toast({ title: "Stage Advanced Successfully", description: `Collection status updated to ${updates.status}` });
      if (onSuccess) onSuccess(data);
      return { success: true, data };
    } catch (error) {
      console.error('Error advancing stage:', error);
      toast({ title: "Update Failed", description: error.message || "Failed to advance collection stage.", variant: "destructive" });
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const subscribeToCollection = useCallback((collectionId, onUpdate) => {
    if (!collectionId) return () => {};
    const channel = supabase
      .channel(`collection-detail-${collectionId}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'collections', filter: `id=eq.${collectionId}` },
        (payload) => { if (payload.new && onUpdate) onUpdate(payload.new); }
      )
      .subscribe();
    return () => { supabase.removeChannel(channel); };
  }, []);

  return { advanceStage, subscribeToCollection, loading };
}
