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

export interface Task {
  id: string;
  contact_id: string | null;
  owner_id: string;
  title: string;
  description: string | null;
  due_date: string | null;
  completed_at: string | null;
  status: 'pending' | 'completed' | 'overdue';
  priority: 'low' | 'medium' | 'high';
  type: 'call' | 'email' | 'meeting' | 'follow-up' | 'other';
  created_at: string;
  updated_at: string;
}

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

  const tasksQuery = useQuery({
    queryKey: ['tasks', contactId],
    queryFn: async () => {
      let query = supabase
        .from('tasks')
        .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 Task[];
    },
    enabled: !!user,
  });

  const createMutation = useMutation({
    mutationFn: async (task: Omit<Task, 'id' | 'created_at' | 'updated_at' | 'owner_id'>) => {
      if (!user) throw new Error('User not authenticated');

      const { data, error } = await supabase
        .from('tasks')
        .insert({
          ...task,
          owner_id: user.id,
        })
        .select()
        .single();

      if (error) throw error;
      return data as Task;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      toast.success('Task created successfully');
      
      // Log activity
      if (user && data.contact_id) {
        logTaskActivity(user.id, data.contact_id, 'created', data.title);
      }
    },
    onError: (error) => {
      toast.error('Failed to create task: ' + error.message);
    },
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, ...updates }: Partial<Task> & { id: string }) => {
      const { data, error } = await supabase
        .from('tasks')
        .update(updates)
        .eq('id', id)
        .select()
        .single();

      if (error) throw error;
      return data as Task;
    },
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      toast.success('Task updated successfully');
      
      // Log activity for completion
      if (user && data.contact_id && variables.status === 'completed') {
        logTaskActivity(user.id, data.contact_id, 'completed', data.title);
      }
    },
    onError: (error) => {
      toast.error('Failed to update task: ' + error.message);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (task: Task) => {
      const { error } = await supabase
        .from('tasks')
        .delete()
        .eq('id', task.id);

      if (error) throw error;
      return task;
    },
    onSuccess: (task) => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      toast.success('Task deleted successfully');
      
      // Log activity
      if (user && task.contact_id) {
        logTaskActivity(user.id, task.contact_id, 'deleted', task.title);
      }
    },
    onError: (error) => {
      toast.error('Failed to delete task: ' + error.message);
    },
  });

  const toggleComplete = async (task: Task) => {
    const isCompleting = task.status !== 'completed';
    await updateMutation.mutateAsync({
      id: task.id,
      status: isCompleting ? 'completed' : 'pending',
      completed_at: isCompleting ? new Date().toISOString() : null,
    });
  };

  return {
    tasks: tasksQuery.data ?? [],
    isLoading: tasksQuery.isLoading,
    createTask: createMutation.mutateAsync,
    updateTask: updateMutation.mutateAsync,
    deleteTask: (task: Task) => deleteMutation.mutateAsync(task),
    toggleComplete,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending,
  };
}
