import cx from "classnames";
import React from "react";

import breakpoints from "../../styles/export/breakpoint";

const overlayBreakpoints: { [key: string]: string } = {
  ...breakpoints,
  xxxl: "1920px",
};

interface ImageSrcObject {
  default: string;
  xxxl?: string;
  xxl?: string;
  xl?: string;
  lg?: string;
  md?: string;
  sm?: string;
  xs?: string;
  [key: string]: string | undefined;
}

interface ImageProps {
  alt: string;
  src: string | ImageSrcObject;
  className?: string;
  [key: string]: any;
}

const CLASS_ROOT = "img";

const Image: React.FC<ImageProps> = ({ className, src, alt, ...other }) => {
  const classes = cx(CLASS_ROOT, className);

  if (typeof src === "object") {
    // autocorrect to descending keys
    const descendingSrcKeys = Object.keys(src).sort(
      (a, b) =>
        parseInt(overlayBreakpoints[b]) - parseInt(overlayBreakpoints[a]),
    );
    // this could be done via conditional rendering, but that breaks <ComponentDocs /> ¯\_(ツ)_/¯
    return (
      <picture className={classes}>
        {descendingSrcKeys.map(
          (breakpoint) =>
            breakpoint !== "default" && (
              <source
                key={breakpoint}
                srcSet={src[breakpoint]}
                media={`(min-width: ${overlayBreakpoints[breakpoint]})`}
              />
            ),
        )}
        <img src={src.default} alt={alt} {...other} />
      </picture>
    );
  }

  return <img className={classes} src={src} alt={alt} {...other} />;
};

Image.displayName = "Image";

export { Image };
