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

export type Tag = Tables<'tags'>;

export function useTags() {
    return useQuery({
        queryKey: ['tags'],
        queryFn: async () => {
            const { data, error } = await supabase
                .from('tags')
                .select('*')
                .order('name');

            if (error) throw error;
            return data;
        },
    });
}

interface AddTagParams {
    tagId: string;
    tagName: string;
}

interface RemoveTagParams {
    tagId: string;
    tagName: string;
}

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

    const addTagMutation = useMutation({
        mutationFn: async ({ tagId, tagName }: AddTagParams) => {
            const { error } = await supabase
                .from('contact_tags')
                .insert({
                    contact_id: contactId,
                    tag_id: tagId,
                });

            if (error) throw error;

            return tagName;
        },
        onSuccess: (tagName) => {
            queryClient.invalidateQueries({ queryKey: ['contact', contactId] });
            queryClient.invalidateQueries({ queryKey: ['contacts'] });
            queryClient.invalidateQueries({ queryKey: ['tags'] });
            toast.success('Tag added');

            if (user) {
                logTagChange(user.id, contactId, 'added', tagName);
            }
        },
        onError: (error) => {
            toast.error('Failed to add tag: ' + error.message);
        },
    });

    const removeTagMutation = useMutation({
        mutationFn: async ({ tagId, tagName }: RemoveTagParams) => {
            const { error } = await supabase
                .from('contact_tags')
                .delete()
                .eq('contact_id', contactId)
                .eq('tag_id', tagId);

            if (error) throw error;

            return tagName;
        },
        onSuccess: (tagName) => {
            queryClient.invalidateQueries({ queryKey: ['contact', contactId] });
            queryClient.invalidateQueries({ queryKey: ['contacts'] });
            toast.success('Tag removed');

            if (user) {
                logTagChange(user.id, contactId, 'removed', tagName);
            }
        },
        onError: (error) => {
            toast.error('Failed to remove tag: ' + error.message);
        },
    });

    const addTag = (tagId: string, tagName: string) => {
        return addTagMutation.mutateAsync({ tagId, tagName });
    };

    const removeTag = (tagId: string, tagName: string) => {
        return removeTagMutation.mutateAsync({ tagId, tagName });
    };

    return {
        addTag,
        removeTag,
        isAdding: addTagMutation.isPending,
        isRemoving: removeTagMutation.isPending,
    };
}