import React, { useState } from 'react';
import { Box, BoxProps } from './primitives/Box';
import { ImagePlaceholder } from './ImagePlaceholder';

export interface ImageProps extends Omit<BoxProps<'img'>, 'children'> {
  src: string;
  alt: string;
  fallbackSrc?: string;
  fallbackComponent?: React.ReactNode;
}

export const Image = ({ 
  src, 
  alt, 
  fallbackSrc,
  fallbackComponent,
  ...props 
}: ImageProps) => {
  const [error, setError] = useState(false);

  if (error) {
    if (fallbackComponent) return <>{fallbackComponent}</>;
    if (fallbackSrc) return <Box as="img" src={fallbackSrc} alt={alt} {...props} />;
    return <ImagePlaceholder />;
  }

  return (
    <Box 
      as="img" 
      src={src} 
      alt={alt} 
      onError={() => setError(true)} 
      {...props} 
    />
  );
};
