import React from 'react';
import useProgressiveImage from '../../hooks/useProgressiveImage';
import { FilledCheckmarkIcon } from '../../icons';
// @ts-ignore
import { BlockImage, BlockWrapper, FilledCheckmarkWrapper } from './styles';

type SelectableBlockProps = {
  src: string;
  onBlockClick: (src: string) => void;
  isSelected: boolean;
  altText?: string;
  width: number;
};

const SelectableBlock: React.FC<SelectableBlockProps> = ({
  src,
  onBlockClick,
  isSelected,
  altText,
  width,
}) => {
  const { sourceLoaded, imageHeight, imageWidth } = useProgressiveImage(src);
  const blockWrapperClickHandler = () => {
    onBlockClick(src);
  };
  return (
    <BlockWrapper
      role="img"
      aria-label={altText || 'image'}
      onClick={() => blockWrapperClickHandler()}
      height={generateImageHeight(imageHeight, imageWidth, width)}
      width={width}
      src={sourceLoaded}
    >
      <BlockImage
        id={src}
        height={generateImageHeight(imageHeight, imageWidth, width)}
        width={width}
        src={sourceLoaded}
      />
      {isSelected && (
        <FilledCheckmarkWrapper width={width}>
          <FilledCheckmarkIcon />
        </FilledCheckmarkWrapper>
      )}
    </BlockWrapper>
  );
};

const generateImageHeight = (
  imageHeight: number,
  imageWidth: number,
  width: number
) => {
  return (width * imageHeight) / imageWidth;
};

export default SelectableBlock;
