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

export function useContactAvatar(contactId: string) {
  const queryClient = useQueryClient();

  const uploadMutation = useMutation({
    mutationFn: async (file: File) => {
      // Get current avatar URL to delete old file
      const { data: contact } = await supabase
        .from('contacts')
        .select('avatar_url')
        .eq('id', contactId)
        .single();

      // Delete old avatar if exists
      if (contact?.avatar_url) {
        const oldPath = contact.avatar_url.split('/avatars/')[1];
        if (oldPath) {
          await supabase.storage.from('avatars').remove([oldPath]);
        }
      }

      // Generate unique file path
      const fileExt = file.name.split('.').pop();
      const fileName = `${contactId}/${Date.now()}.${fileExt}`;

      // Upload new avatar
      const { error: uploadError } = await supabase.storage
        .from('avatars')
        .upload(fileName, file, { upsert: true });

      if (uploadError) throw uploadError;

      // Get public URL
      const { data: { publicUrl } } = supabase.storage
        .from('avatars')
        .getPublicUrl(fileName);

      // Update contact with new avatar URL
      const { error } = await supabase
        .from('contacts')
        .update({ avatar_url: publicUrl })
        .eq('id', contactId);

      if (error) {
        // Clean up uploaded file if update fails
        await supabase.storage.from('avatars').remove([fileName]);
        throw error;
      }

      return publicUrl;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contact', contactId] });
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
      toast.success('Avatar updated successfully');
    },
    onError: (error) => {
      toast.error('Failed to upload avatar: ' + error.message);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async () => {
      // Get current avatar URL
      const { data: contact } = await supabase
        .from('contacts')
        .select('avatar_url')
        .eq('id', contactId)
        .single();

      if (contact?.avatar_url) {
        const filePath = contact.avatar_url.split('/avatars/')[1];
        if (filePath) {
          await supabase.storage.from('avatars').remove([filePath]);
        }
      }

      // Update contact to remove avatar URL
      const { error } = await supabase
        .from('contacts')
        .update({ avatar_url: null })
        .eq('id', contactId);

      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contact', contactId] });
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
      toast.success('Avatar removed');
    },
    onError: (error) => {
      toast.error('Failed to remove avatar: ' + error.message);
    },
  });

  return {
    uploadAvatar: uploadMutation.mutateAsync,
    deleteAvatar: deleteMutation.mutateAsync,
    isUploading: uploadMutation.isPending,
    isDeleting: deleteMutation.isPending,
  };
}
