import { supabase } from '@/integrations/supabase/client';

export const isValidImageFormat = (url) => {
  if (!url) return false;
  return /\.(jpg|jpeg|png|webp|avif|gif)(\?.*)?$/i.test(url) || 
         url.includes('violation-photos') || 
         url.includes('images');
};

export const fetchImageForPdf = async (url) => {
  if (!url) return null;

  try {
    const extension = url.split('.').pop().split('?')[0].toLowerCase();
    let format = 'JPEG';
    if (extension === 'png') format = 'PNG';
    if (extension === 'webp') format = 'WEBP';

    const response = await fetch(url);
    if (!response.ok) throw new Error(`Failed to fetch image: ${response.statusText}`);
    
    const blob = await response.blob();
    
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        const base64data = reader.result;
        
        const img = new Image();
        img.onload = () => {
          resolve({
            data: base64data,
            width: img.width,
            height: img.height,
            format
          });
        };
        img.onerror = () => {
          console.warn(`Could not load image dimensions for ${url}`);
          resolve(null); 
        };
        img.src = base64data;
      };
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  } catch (error) {
    console.warn(`Error processing image ${url}:`, error);
    return null;
  }
};

export const calculateImageDimensions = (srcWidth, srcHeight, maxWidth = 300, maxHeight = 400) => {
  if (!srcWidth || !srcHeight) return { width: 0, height: 0 };

  const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
  
  if (ratio >= 1) {
      return { width: srcWidth, height: srcHeight };
  }

  return {
    width: srcWidth * ratio,
    height: srcHeight * ratio
  };
};

export const prepareTimelineImages = async (entries, onProgress) => {
  const enrichedEntries = [];
  let successCount = 0;
  let errorCount = 0;
  
  const entriesWithImages = entries.filter(e => 
    e.image_url || (e.attachments && e.attachments.find(a => isValidImageFormat(a.url)))
  );
  
  const totalImages = entriesWithImages.length;
  let processedImages = 0;

  const allEntries = JSON.parse(JSON.stringify(entries));

  for (const entry of allEntries) {
    let imageUrl = entry.image_url;
    
    if (!imageUrl && entry.attachments && Array.isArray(entry.attachments)) {
        const validAttach = entry.attachments.find(a => isValidImageFormat(a.url));
        if (validAttach) imageUrl = validAttach.url;
    }

    if (imageUrl) {
      const imageData = await fetchImageForPdf(imageUrl);
      
      processedImages++;
      if (onProgress) {
        onProgress(Math.round((processedImages / totalImages) * 100));
      }

      if (imageData) {
        entry.imageData = imageData;
        successCount++;
      } else {
        errorCount++;
        entry.imageError = true;
      }
    }
    
    enrichedEntries.push(entry);
  }

  return { enrichedEntries, successCount, errorCount };
};
