import React from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';

import { ASSET_PROP_TYPE, getImageFromField } from '../utils';
import { Background } from '../background';

const DEFAULT_STYLES = {
  width: '100%',
  height: '100%',
  left: 0,
  top: 0,
  position: 'fixed',
  zIndex: -1,
  objectFit: 'cover',
  pointerEvents: 'none',
  overflow: 'hidden'
};

/**
 * A component that will try to eagerly load a blured placeholder and lazy load the actual
 * background
 */
export const LazyBackground = (props) => {
  const { style, landscape, portrait, preloadPlaceholder, getImageUrl, ...restProps } = props;

  const landscapeUrl = getImageFromField(landscape);
  const portraitUrl = getImageFromField(portrait);
  const defaultUrl = landscapeUrl || portraitUrl;

  const containerStyles = { ...DEFAULT_STYLES, ...style };
  const placeholderUrl = getImageUrl(defaultUrl, { w: 100, h: 100 });

  return (
    <div style={containerStyles}>
      {preloadPlaceholder && (
        <Helmet>
          <link rel="preload" href={placeholderUrl} as="image" />
        </Helmet>
      )}
      <img
        src={placeholderUrl}
        alt=""
        loading="eager"
        style={{
          ...containerStyles,
          width: '100%',
          height: '100%',
          left: 0,
          top: 0,
          position: 'absolute',
          filter: 'blur(4px)'
        }}
      />
      <Background
        {...restProps}
        landscape={landscape}
        portrait={portrait}
        style={{
          ...style,
          position: 'absolute'
        }}
        loading="lazy"
      />
    </div>
  );
};

LazyBackground.propTypes = {
  /** Landscape background image */
  landscape: ASSET_PROP_TYPE,

  /** Portrait background image */
  portrait: ASSET_PROP_TYPE,

  /** Custom styles */
  style: PropTypes.object, // eslint-disable-line react/forbid-prop-types

  /** Preload placeholder image */
  preloadPlaceholder: PropTypes.bool,

  getImageUrl: PropTypes.func.isRequired
};

LazyBackground.defaultProps = {
  landscape: null,
  portrait: null,
  style: {},
  preloadPlaceholder: false
};
