import { toast } from "sonner";
import config from "@/config";
import { Product, ProductImageSortable } from "../types";

interface UseProductImageOperationsProps {
  data: Product[];
  productImages: ProductImageSortable[];
  setProductImages: React.Dispatch<React.SetStateAction<ProductImageSortable[]>>;
}

export const useProductImageOperations = ({
  data,
  productImages,
  setProductImages,
}: UseProductImageOperationsProps) => {
  // Function to remove an image URL from a product
  const removeImageFromProduct = (productIndex: number, imageUrl: string) => {
    // Create a copy of the data
    const newData = [...data];
    
    // Get the current product
    const product = newData[productIndex];
    
    // We need to update product_images array directly instead of the image_url field
    if (!product.product_images) {
      product.product_images = [];
    } else if (typeof product.product_images === 'string') {
      // Handle case where it might be a comma-separated string
      product.product_images = product.product_images.split(',').filter(Boolean);
    }
    
    // Filter out the image URL we're removing
    if (Array.isArray(product.product_images)) {
      product.product_images = product.product_images.filter((url: string) => url && url !== imageUrl);
    }
    
    return newData;
  };
  
  // Function to add an image URL to a product
  const addImageToProduct = (productIndex: number, imageUrl: string) => {
    // Create a copy of the data
    const newData = [...data];
    
    // Get the current product
    const product = newData[productIndex];
    
    // Initialize product_images array if it doesn't exist
    if (!product.product_images) {
      product.product_images = [];
    } else if (typeof product.product_images === 'string') {
      // Handle case where it might be a comma-separated string
      product.product_images = product.product_images.split(',').filter(Boolean);
    }
    
    // Ensure it's an array
    if (!Array.isArray(product.product_images)) {
      product.product_images = [product.product_images].filter(Boolean);
    }
    
    // Only add if the URL doesn't already exist
    if (!product.product_images.includes(imageUrl)) {
      product.product_images.push(imageUrl);
    }
    
    return newData;
  };

  // Function to handle image upload - update product data
  const handleImageUpload = async (files: FileList | File[], productIndex: number) => {
    if (!files || files.length === 0) return;
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // Add placeholder for this image
      const newImage: ProductImageSortable = {
        id: `image-${productIndex}-${Date.now()}-${i}`, // Generate a unique ID
        productIndex,
        imageUrl: '',
        loading: true,
        fileName: file.name,
        // Add required schema fields for ProductImageSortable
        pid: data[productIndex].id || 0,
        iid: 0,
        type: 0, 
        order: 0,
        width: 0,
        height: 0,
        hidden: 0
      };
      
      setProductImages(prev => [...prev, newImage]);
      
      // Create form data for upload
      const formData = new FormData();
      formData.append('image', file);
      formData.append('productIndex', productIndex.toString());
      formData.append('upc', data[productIndex].upc || '');
      formData.append('supplier_no', data[productIndex].supplier_no || '');
      
      try {
        // Upload the image
        const response = await fetch(`${config.apiUrl}/import/upload-image`, {
          method: 'POST',
          body: formData,
        });
        
        if (!response.ok) {
          throw new Error('Failed to upload image');
        }
        
        const result = await response.json();
        
        // Update the image URL in our state
        setProductImages(prev => 
          prev.map(img => 
            (img.loading && img.productIndex === productIndex && img.fileName === file.name) 
              ? { ...img, imageUrl: result.imageUrl, loading: false }
              : img
          )
        );
        
        // Update the product data with the new image URL
        addImageToProduct(productIndex, result.imageUrl);
        
        toast.success(`Image uploaded for ${data[productIndex].name || `Product #${productIndex + 1}`}`);
      } catch (error) {
        console.error('Upload error:', error);
        
        // Remove the failed image from our state
        setProductImages(prev => 
          prev.filter(img => 
            !(img.loading && img.productIndex === productIndex && img.fileName === file.name)
          )
        );
        
        toast.error(`Failed to upload image: ${error instanceof Error ? error.message : 'Unknown error'}`);
      }
    }
  };
  
  // Function to remove an image - update to work with product_images
  const removeImage = async (imageIndex: number) => {
    const image = productImages[imageIndex];
    if (!image) return;
    
    try {
      // Check if this is an external URL-based image or an uploaded image
      const isExternalUrl = image.imageUrl.startsWith('http') && 
        !image.imageUrl.includes(config.apiUrl.replace(/^https?:\/\//, ''));
      
      // Only call the API to delete the file if it's an uploaded image
      if (!isExternalUrl) {
        // Extract the filename from the URL
        const urlParts = image.imageUrl.split('/');
        const filename = urlParts[urlParts.length - 1];
        
        // Call API to delete the image
        const response = await fetch(`${config.apiUrl}/import/delete-image`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ 
            imageUrl: image.imageUrl,
            filename
          }),
        });
        
        if (!response.ok) {
          throw new Error('Failed to delete image');
        }
      }
      
      // Remove the image from our state
      setProductImages(prev => prev.filter((_, idx) => idx !== imageIndex));
      
      // Remove the image URL from the product data
      removeImageFromProduct(image.productIndex, image.imageUrl);
      
      toast.success('Image removed successfully');
    } catch (error) {
      console.error('Delete error:', error);
      toast.error(`Failed to remove image: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  };

  return {
    removeImageFromProduct,
    addImageToProduct,
    handleImageUpload,
    removeImage,
  };
}; 