import React, { useState } from 'react';
import { Box } from '@mui/material';
import imageUtils from '@utils/imageUtils';

/**
 * Component to display product images with fallback handling
 * @param {Object} props - Component props
 * @param {Array|Object|string} props.images - Product images array, single image object, or image path
 * @param {string} props.alt - Alt text for the image
 * @param {Object} props.sx - Additional styling props
 * @param {string} props.placeholderImage - Placeholder image to use when no image is available
 * @returns {JSX.Element} - ProductImage component
 */
const ProductImage = ({ 
  images, 
  alt = 'Product image', 
  sx = {}, 
  placeholderImage = '/placeholder.jpg',
  ...rest 
}) => {
  const [imageError, setImageError] = useState(false);
  
  // Determine which image to use
  let imageSrc = placeholderImage;
  
  // Handle different types of image inputs
  if (Array.isArray(images) && images.length > 0) {
    // Find primary image in the array
    const primaryImage = images.find(img => img.isPrimary || img.is_primary) || images[0];
    const imagePath = primaryImage.path || primaryImage.image_path || primaryImage;
    imageSrc = imageUtils.getImageUrl(imagePath, placeholderImage);
  } else if (typeof images === 'object' && images !== null) {
    // Single image object
    const imagePath = images.path || images.image_path;
    imageSrc = imageUtils.getImageUrl(imagePath, placeholderImage);
  } else if (typeof images === 'string' && images) {
    // Direct image path
    imageSrc = imageUtils.getImageUrl(images, placeholderImage);
  }
  
  // Handle image load errors
  const handleError = () => {
    console.error(`Failed to load image: ${imageSrc}`);
    if (!imageError) {
      setImageError(true);
    }
  };
  
  return (
    <Box
      component="img"
      src={imageError ? placeholderImage : imageSrc}
      alt={alt}
      onError={handleError}
      sx={{
        display: 'block',
        width: '100%',
        height: 'auto',
        objectFit: 'cover',
        ...sx
      }}
      {...rest}
    />
  );
};

export default ProductImage;