import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';

export type ActivityCategory = 'system' | 'user' | 'automation';

export interface Activity {
  id: string;
  contact_id: string;
  user_id: string;
  type: 'email' | 'sms' | 'call' | 'system';
  direction: 'inbound' | 'outbound' | 'log';
  subject?: string | null;
  body_preview?: string | null;
  status: string;
  category: ActivityCategory;
  created_at: string;
}

export function useActivities(contactId?: string) {
  const queryClient = useQueryClient();
  const { user } = useAuth();

  const activitiesQuery = useQuery({
    queryKey: ['activities', contactId],
    queryFn: async () => {
      let query = supabase
        .from('activities')
        .select('*')
        .order('created_at', { ascending: false });

      if (contactId) {
        query = query.eq('contact_id', contactId);
      }

      const { data, error } = await query;
      if (error) throw error;
      return data as Activity[];
    },
    enabled: !!contactId,
  });

  const createMutation = useMutation({
    mutationFn: async (activity: Omit<Activity, 'id' | 'created_at' | 'user_id'>) => {
      if (!user) throw new Error('User not authenticated');
      
      const { data, error } = await supabase
        .from('activities')
        .insert({
          ...activity,
          user_id: user.id,
        })
        .select()
        .single();

      if (error) throw error;
      return data as Activity;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['activities'] });
    },
    onError: (error) => {
      toast.error('Failed to log activity: ' + error.message);
    },
  });

  return {
    activities: activitiesQuery.data ?? [],
    isLoading: activitiesQuery.isLoading,
    logActivity: createMutation.mutateAsync,
    isLogging: createMutation.isPending,
    refetch: activitiesQuery.refetch,
  };
}
