import React from 'react';
import styled from 'styled-components';

import { parseSrcSet } from '@redocly/theme/core/utils';

export type ImageProps = {
  src?: string;
  srcSet?: string;
  alt?: string;
  className?: string;
  width?: string | number;
  height?: string | number;
  border?: string;
  withLightbox?: boolean;
  style?: React.CSSProperties | string;
};

export function Image(props: ImageProps): JSX.Element {
  const { src, srcSet, alt, className, width, height, border, style, withLightbox } = props;

  const [lightboxImage, setLightboxImage] = React.useState<string | undefined>(undefined);
  const parsedSourceSetMap = React.useMemo(() => {
    return srcSet ? parseSrcSet(srcSet) : new Map();
  }, [srcSet]);

  const handleImageClick = (src: string) => {
    if (!withLightbox || lightboxImage) {
      return;
    }
    setLightboxImage(src);
  };

  const handleCloseLightbox = () => {
    setLightboxImage(undefined);
  };

  const combinedStyles: React.CSSProperties = {
    ...(withLightbox && { cursor: 'pointer' }),
    ...(border && { border }),
    ...(typeof style === 'string' ? { cssText: style } : style),
  };

  return (
    <>
      {lightboxImage ? (
        <LightboxContainer onClick={handleCloseLightbox}>
          <Image src={lightboxImage} alt={alt} />
        </LightboxContainer>
      ) : null}
      {src ? (
        <img
          src={src}
          alt={alt}
          className={className}
          width={width}
          height={height}
          style={combinedStyles}
          onClick={() => handleImageClick(src)}
        />
      ) : (
        Array.from(parsedSourceSetMap).map(([key, value]) => (
          <ColorModeAwareImage
            key={key}
            colorMode={key}
            src={value}
            alt={alt}
            className={className}
            width={width}
            height={height}
            $withLightbox={withLightbox}
            style={combinedStyles}
            onClick={() => handleImageClick(value)}
          />
        ))
      )}
    </>
  );
}

const ColorModeAwareImage = styled.img<{ colorMode: string; $withLightbox?: boolean }>`
  html:not(.${(props) => props.colorMode}) && {
    display: none;
  }
  ${({ $withLightbox }) =>
    $withLightbox &&
    `
    cursor: pointer;
  `}
`;

const LightboxContainer = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--bg-color-modal-overlay);
  z-index: var(--z-index-overlay);
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    cursor: pointer;
    max-width: 90%;
    max-height: 90%;
  }
`;
