
import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
import { ImageCompressor, CompressionOptions } from '@/components/admin/image-upload/ImageCompressor';

export interface UseImageUploadOptions {
  maxSizeInMB?: number;
  allowedTypes?: string[];
  folder?: string;
  compression?: CompressionOptions;
  enableCompression?: boolean;
}

export const useImageUpload = (options: UseImageUploadOptions = {}) => {
  const {
    maxSizeInMB = 2,
    allowedTypes = ['image/jpeg', 'image/png', 'image/webp'],
    folder = 'uploads',
    compression,
    enableCompression = true
  } = options;

  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);

  const uploadImage = async (file: File): Promise<string | null> => {
    if (!file) return null;

    // Validation de la taille initiale
    if (file.size > maxSizeInMB * 1024 * 1024) {
      toast.error(`L'image doit faire moins de ${maxSizeInMB}MB`);
      return null;
    }

    // Validation du type
    if (!allowedTypes.includes(file.type)) {
      toast.error('Format d\'image non supporté. Utilisez JPG, PNG ou WebP.');
      return null;
    }

    setUploading(true);
    setProgress(0);

    try {
      let processedFile = file;

      // Compression si activée
      if (enableCompression && (file.type === 'image/jpeg' || file.type === 'image/png')) {
        setProgress(20);
        toast.info('Compression de l\'image...');
        
        try {
          const compressionOptions: CompressionOptions = {
            maxWidth: folder === 'avatars' ? 512 : 1920,
            maxHeight: folder === 'avatars' ? 512 : 1080,
            quality: 0.85,
            outputFormat: 'image/jpeg',
            ...compression
          };
          
          processedFile = await ImageCompressor.compressImage(file, compressionOptions);
          
          // Vérifier si la compression a réduit la taille
          if (processedFile.size < file.size) {
            const savedKB = Math.round((file.size - processedFile.size) / 1024);
            toast.success(`Image compressée (${savedKB}KB économisés)`);
          }
        } catch (error) {
          console.warn('Compression échouée, utilisation du fichier original:', error);
          processedFile = file;
        }
      }

      setProgress(40);

      const fileExt = processedFile.name.split('.').pop();
      const fileName = `${folder}/${Date.now()}-${Math.random().toString(36).substring(2)}.${fileExt}`;

      setProgress(60);

      const { error: uploadError, data } = await supabase.storage
        .from('images')
        .upload(fileName, processedFile, {
          cacheControl: '3600',
          upsert: false
        });

      if (uploadError) {
        console.error('Upload error:', uploadError);
        toast.error('Erreur lors de l\'upload de l\'image');
        return null;
      }

      setProgress(80);

      // Récupérer l'URL publique
      const { data: { publicUrl } } = supabase.storage
        .from('images')
        .getPublicUrl(fileName);

      setProgress(100);
      
      // Petit délai pour voir la progression complète
      setTimeout(() => {
        toast.success('Image uploadée avec succès');
      }, 200);

      return publicUrl;
    } catch (error) {
      console.error('Upload error:', error);
      toast.error('Erreur lors de l\'upload');
      return null;
    } finally {
      setTimeout(() => {
        setUploading(false);
        setProgress(0);
      }, 500);
    }
  };

  const validateImageDimensions = async (
    file: File,
    minWidth?: number,
    minHeight?: number,
    maxWidth?: number,
    maxHeight?: number
  ): Promise<boolean> => {
    try {
      const dimensions = await ImageCompressor.getImageDimensions(file);
      
      if (minWidth && dimensions.width < minWidth) {
        toast.error(`L'image doit faire au moins ${minWidth}px de largeur`);
        return false;
      }
      
      if (minHeight && dimensions.height < minHeight) {
        toast.error(`L'image doit faire au moins ${minHeight}px de hauteur`);
        return false;
      }
      
      if (maxWidth && dimensions.width > maxWidth) {
        toast.error(`L'image ne doit pas dépasser ${maxWidth}px de largeur`);
        return false;
      }
      
      if (maxHeight && dimensions.height > maxHeight) {
        toast.error(`L'image ne doit pas dépasser ${maxHeight}px de hauteur`);
        return false;
      }
      
      return true;
    } catch (error) {
      console.error('Erreur validation dimensions:', error);
      return true; // Continue si on ne peut pas valider
    }
  };

  const deleteImage = async (url: string): Promise<boolean> => {
    try {
      // Extraire le nom du fichier de l'URL
      const urlParts = url.split('/');
      const fileName = urlParts.slice(-2).join('/'); // folder/filename

      const { error } = await supabase.storage
        .from('images')
        .remove([fileName]);

      if (error) {
        console.error('Delete error:', error);
        return false;
      }

      toast.success('Image supprimée');
      return true;
    } catch (error) {
      console.error('Delete error:', error);
      return false;
    }
  };

  return {
    uploadImage,
    deleteImage,
    validateImageDimensions,
    uploading,
    progress
  };
};
