/**
 * TEAM: frontend_infra
 * @flow
 */

import * as React from "react";
import {css, StyleSheet} from "aphrodite";

type Props = {|
  /** Image URL */
  +src: string,
  /** Alternate text for accessibility, or if the image failed to load. */
  +alt: string,
  /** Image defaults to width: 100% unless a maxWidth is specified. */
  +maxWidth?: number,
  /** Image height is assumed to be square unless specified. */
  +height?: number,
|};

/**
 * Reusable image loader with CSS fade-in.
 * See Flag.jsx or CarrierLogo.jsx for usage.
 */
function Image({src, alt, maxWidth, height}: Props): React.Element<"img"> {
  const [loaded, setLoaded] = React.useState<boolean>(false);
  const imgHeight = height || maxWidth;

  return (
    <img
      src={src}
      alt={alt}
      className={css(styles.fade, loaded && styles.fadeIn)}
      style={{
        width: maxWidth ? `${maxWidth}px !important` : "100%",
        maxWidth: maxWidth ? `${maxWidth}px` : null,
        height: imgHeight ? `${imgHeight}px` : "auto",
      }}
      onLoad={() => setLoaded(true)}
    />
  );
}

const styles = StyleSheet.create({
  fade: {
    opacity: 0,
    transition: "opacity 0.2s cubic-bezier(.42,0,.58,1)",
  },
  fadeIn: {
    opacity: 1,
  },
});

export default Image;
