'use client'; import { useState, useRef } from 'react'; import { replaceFile, uploadFile } from '@/lib/hooks'; import { toast } from 'sonner'; import { useAuth } from '@/components/context'; import { resizeImage } from '@/lib/hooks'; import type { Result } from '.'; export type Replace = { replace: true; path: string } | false; export type uploadToStorageProps = { file: File; bucket: string; resize: boolean; options?: { maxWidth?: number; maxHeight?: number; quality?: number; }; replace?: Replace; }; export const useFileUpload = () => { const [isUploading, setIsUploading] = useState(false); const fileInputRef = useRef(null); const { profile, isAuthenticated } = useAuth(); const uploadToStorage = async ({ file, bucket, resize = false, options = {}, replace = false, }: uploadToStorageProps): Promise> => { try { if (!isAuthenticated) throw new Error('User is not authenticated'); setIsUploading(true); if (replace) { const updateResult = await replaceFile({ bucket, path: replace.path, file, options: { contentType: file.type, }, }); if (!updateResult.success) { return { success: false, error: updateResult.error }; } else { return { success: true, data: updateResult.data }; } } let fileToUpload = file; if (resize && file.type.startsWith('image/')) fileToUpload = await resizeImage({ file, options }); // Generate a unique filename to avoid collisions const fileExt = file.name.split('.').pop(); const fileName = `${Date.now()}-${profile?.id}.${fileExt}`; // Upload the file to Supabase storage const uploadResult = await uploadFile({ bucket, path: fileName, file: fileToUpload, options: { contentType: file.type, }, }); if (!uploadResult.success) { throw new Error(uploadResult.error || `Failed to upload to ${bucket}`); } return { success: true, data: uploadResult.data }; } catch (error) { toast.error( error instanceof Error ? error.message : `Failed to upload to ${bucket}`, ); return { success: false, error: `Error: ${ error instanceof Error ? error.message : `Failed to upload to ${bucket}` }`, }; } finally { setIsUploading(false); // Clear the input value so the same file can be selected again if (fileInputRef.current) fileInputRef.current.value = ''; } }; return { isUploading, fileInputRef, uploadToStorage, }; };