import React from 'react';
import PropTypes from 'prop-types';
import { graphql, useStaticQuery } from 'gatsby';
import { GatsbyImage } from 'gatsby-plugin-image';

export const PureImage = ({
  filename,
  className = '',
  alt = '',
  height = '100%',
  width = '100%',
  objectFit = 'cover',
  customStyle = null,
  loading = 'eager',
  data,
}) => {
  const image = data && data.images.edges.find((n) => n.node.relativePath.includes(filename));
  if (!image) {
    return null;
  }
  return (
    <GatsbyImage
      className={className || ''}
      loading={loading}
      objectFit={objectFit}
      alt={alt}
      style={customStyle || { height, width }}
      image={image.node.childImageSharp.gatsbyImageData}
    />
  );
};

export const Image = (props) => {
  const data = useStaticQuery(graphql`
    query {
      images: allFile(filter: { extension: { nin: ["svg", "gif", ".gitkeep"] } }) {
        edges {
          node {
            relativePath
            name
            childImageSharp {
              gatsbyImageData(layout: FULL_WIDTH)
            }
          }
        }
      }
    }
  `);

  return <PureImage {...props} data={data} />;
};

PureImage.propTypes = {
  filename: PropTypes.string,
  className: PropTypes.string,
  alt: PropTypes.string,
  height: PropTypes.string,
  objectFit: PropTypes.string,
  loading: PropTypes.string,
  customStyle: PropTypes.shape({}),
  width: PropTypes.string,
  data: PropTypes.shape({
    images: PropTypes.shape({
      edges: PropTypes.arrayOf(PropTypes.shape({})),
    }),
  }),
};

export default Image;
