import { useState } from "react";
import { ProductImageSortable, Product } from "../types";

export const useProductImagesInit = (data: Product[]) => {
  // Initialize product images from data
  const [productImages, setProductImages] = useState<ProductImageSortable[]>(() => {
    // Convert existing product_images to ProductImageSortable objects
    const initialImages: ProductImageSortable[] = [];
    
    data.forEach((product: Product, productIndex: number) => {
      if (product.product_images) {
        let images: any[] = [];
        
        // Handle different formats of product_images
        if (typeof product.product_images === 'string') {
          try {
            // Try to parse as JSON
            images = JSON.parse(product.product_images);
          } catch (e) {
            // If not JSON, split by comma if it's a string
            images = product.product_images.split(',').filter(Boolean).map((url: string) => ({ 
              imageUrl: url.trim(),
              pid: product.id || 0,
              iid: 0,
              type: 0,
              order: 255,
              width: 0,
              height: 0,
              hidden: 0
            }));
          }
        } else if (Array.isArray(product.product_images)) {
          // Use the array directly
          images = product.product_images;
        } else if (product.product_images) {
          // Handle case where it might be a single value
          images = [product.product_images];
        }
        
        // Create ProductImageSortable objects for each image
        images.forEach((img, i) => {
          // Handle both URL strings and structured image objects
          const imageUrl = typeof img === 'string' ? img : img.imageUrl;
          
          if (imageUrl && imageUrl.trim()) {
            initialImages.push({
              id: `image-${productIndex}-initial-${i}`,
              productIndex,
              imageUrl: imageUrl.trim(),
              loading: false,
              fileName: `Image ${i + 1}`,
              // Add schema fields
              pid: product.id || 0,
              iid: typeof img === 'object' && img.iid ? img.iid : i,
              type: typeof img === 'object' && img.type !== undefined ? img.type : 0,
              order: typeof img === 'object' && img.order !== undefined ? img.order : i,
              width: typeof img === 'object' && img.width ? img.width : 0,
              height: typeof img === 'object' && img.height ? img.height : 0,
              hidden: typeof img === 'object' && img.hidden !== undefined ? img.hidden : 0
            });
          }
        });
      }
    });
    
    return initialImages;
  });

  // Function to ensure URLs are properly formatted with absolute paths
  const getFullImageUrl = (url: string): string => {
    // If the URL is already absolute (starts with http:// or https://) return it as is
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    }
    
    // Otherwise, it's a relative URL, prepend the domain
    const baseUrl = 'https://tools.acherryontop.com';
    // Make sure url starts with / for path
    const path = url.startsWith('/') ? url : `/${url}`;
    return `${baseUrl}${path}`;
  };

  return {
    productImages,
    setProductImages,
    getFullImageUrl
  };
}; 