import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';

export function useBusinessLogo() {
  const [isUploading, setIsUploading] = useState(false);

  const uploadLogo = async (businessId: string, file: File, currentLogoUrl?: string | null) => {
    setIsUploading(true);
    try {
      // Delete old logo if exists
      if (currentLogoUrl) {
        const oldPath = currentLogoUrl.split('/').pop();
        if (oldPath) {
          await supabase.storage.from('avatars').remove([`business/${oldPath}`]);
        }
      }

      // Upload new logo
      const fileExt = file.name.split('.').pop();
      const fileName = `${businessId}-${Date.now()}.${fileExt}`;
      const filePath = `business/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from('avatars')
        .upload(filePath, file, { upsert: true });

      if (uploadError) throw uploadError;

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

      // Update business with new logo URL
      const { error: updateError } = await supabase
        .from('business')
        .update({ logo_url: publicUrl })
        .eq('id', businessId);

      if (updateError) throw updateError;

      toast.success('Logo uploaded successfully');
      return publicUrl;
    } catch (error: any) {
      toast.error('Failed to upload logo: ' + error.message);
      throw error;
    } finally {
      setIsUploading(false);
    }
  };

  const deleteLogo = async (businessId: string, logoUrl: string) => {
    try {
      // Extract file path from URL
      const urlParts = logoUrl.split('/');
      const fileName = urlParts[urlParts.length - 1];
      const filePath = `business/${fileName}`;

      // Delete from storage
      const { error: deleteError } = await supabase.storage
        .from('avatars')
        .remove([filePath]);

      if (deleteError) throw deleteError;

      // Update business to remove logo URL
      const { error: updateError } = await supabase
        .from('business')
        .update({ logo_url: null })
        .eq('id', businessId);

      if (updateError) throw updateError;

      toast.success('Logo deleted successfully');
    } catch (error: any) {
      toast.error('Failed to delete logo: ' + error.message);
      throw error;
    }
  };

  return {
    uploadLogo,
    deleteLogo,
    isUploading,
  };
}
