import { memo } from 'react';
import React from 'react';
import { getImageProps } from 'next/image';
import breakpoints from './breakpoints';

export type Image = {
  url: string;
  width: number;
  height: number;
  alternativeText?: string;
};

export interface ResponsiveImageProps
  extends React.HTMLAttributes<HTMLImageElement> {
  src: string;
  width: number;
  height: number;
  sizes: string;
  alt?: string;
  priority?: boolean;
  quality?: number;
  children?: React.ReactNode;
}

export interface SourceProps extends React.HTMLAttributes<HTMLSourceElement> {
  src: string;
  width: number;
  height: number;
  media: string;
  sizes: string;
  quality?: number;
}

const ResponsiveImage: React.FC<ResponsiveImageProps> & {
  Source: React.FC<SourceProps>;
} = ({
  src,
  width,
  height,
  alt,
  sizes,
  quality,
  priority,
  children,
  ...rest
}) => {
  if (src) {
    const { props } = getImageProps({
      src,
      width,
      height,
      sizes,
      quality,
      priority,
      alt: alt || ''
    });

    return (
      <picture>
        {children}
        <img {...props} {...rest} alt={alt || ''} />
      </picture>
    );
  }
};

ResponsiveImage.Source = memo(
  ({ src, width, height, sizes, media, quality, ...rest }: SourceProps) => {
    if (src) {
      const query = breakpoints[media] || media;
      const { props } = getImageProps({
        width,
        height,
        src,
        sizes,
        quality,
        alt: ''
      });

      return (
        <source
          media={query}
          src={props.src}
          srcSet={props.srcSet}
          width={props.width}
          height={props.height}
          sizes={props.sizes}
          {...rest}
        />
      );
    }
  }
);

ResponsiveImage.displayName = 'ResponsiveImage';
ResponsiveImage.Source.displayName = 'ResponsiveImageSource';

export default ResponsiveImage;
