import { useEffect, useState } from 'react';

import { Stack, type SxProps, useTheme } from '@mui/material';

import ImageSkeleton from './skeleton';
import { type ImageProps } from './types';

const Image = ({
  src,
  defaultSrc,
  alt = '',
  aspectRatio = '2/1',
  sx = {},
  loading = false,
}: ImageProps) => {
  const [imgUrl, setImgUrl] = useState(src ?? defaultSrc);

  const { shape } = useTheme();

  useEffect(() => {
    setImgUrl(src ?? defaultSrc);
  }, [src, defaultSrc]);

  const handleImgError = () => setImgUrl(defaultSrc);

  const commonSx = {
    borderRadius: shape.borderRadiusL,
    aspectRatio,
    ...sx,
  } as SxProps;

  if (loading) {
    return <ImageSkeleton sx={commonSx} />;
  }

  return (
    <Stack
      component="img"
      src={imgUrl}
      alt={alt}
      onError={handleImgError}
      sx={{
        objectFit: 'cover',
        ...commonSx,
      }}
    />
  );
};

export default Image;
