import { useState, useCallback } from 'react';
import imageCompression from 'browser-image-compression';

export interface ImageCompressOptions {
  maxSizeMB?: number;
  maxWidthOrHeight?: number;
  useWebWorker?: boolean;
}

export interface CompressionResult {
  file: File;
  originalSize: number;
  compressedSize: number;
}

/**
 * Compresses an image file using browser-image-compression.
 * Runs in a WebWorker by default to avoid blocking the main thread.
 */
export function useImageCompress() {
  const [isCompressing, setIsCompressing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const compress = useCallback(async (
    file: File,
    options: ImageCompressOptions = {}
  ): Promise<CompressionResult> => {
    setIsCompressing(true);
    setError(null);

    const defaultOptions = {
      maxSizeMB: 1,
      maxWidthOrHeight: 1920,
      useWebWorker: true,
      fileType: file.type,
      ...options,
    };

    try {
      const compressed = await imageCompression(file, defaultOptions);
      setIsCompressing(false);
      return {
        file: compressed as File,
        originalSize: file.size,
        compressedSize: compressed.size,
      };
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Compression failed';
      setError(msg);
      setIsCompressing(false);
      throw e;
    }
  }, []);

  return { compress, isCompressing, error };
}
