import type { FC, HTMLAttributes } from 'react';
import React from 'react';

/**
 * todo:
 * - calculate intrinsic dimensions of image without using <img> height and width attributes https://amp.dev/documentation/guides-and-tutorials/learn/amp-html-layout/layouts_demonstrated/?format=websites#intrinsic
 * - automatically generate a srcset attribute, if one isn't passed, based on style system breakpoints
 * - figure out a better way to set CDN_URL. context? requires wrapping of app in provider... this might be ok if we ever allow theming. other options?
 */

let CDN_URL: string;

// CRA and Next.js

if (typeof process !== 'undefined') {
  CDN_URL = process.env.REACT_APP_CDN_URL ?? process.env.NEXT_PUBLIC_CDN_URL ?? 'https://cdn.britannica.com';
}

// Mendel and a default (this can't be a long term solution :grimace:)
else {
  // @ts-ignore
  CDN_URL = window.Mendel?.config.cdnUrl ?? 'https://cdn.britannica.com';
}

export interface IrisImageProps extends Omit<HTMLAttributes<HTMLImageElement>, 'children'> {
  children?: Function;
  src: string;
  alt: string;
  loading?: 'lazy' | 'eager';
  quality?: string | number;
  height?: string | number;
  width?: string | number;
  size?: string;
  command?: string;
  imgHeight?: string | number;
  imgWidth?: string | number;
}

const IrisImage: FC<IrisImageProps> = ({
  children,
  src,
  alt,
  loading = 'lazy',
  quality,
  height,
  width,
  size,
  command,
  imgHeight,
  imgWidth,
  ...rest
}) => {
  const irisParams = new URLSearchParams();

  if (command) {
    irisParams.append('c', command);
  }

  if (height) {
    irisParams.append('h', height.toString());
  }

  if (width) {
    irisParams.append('w', width.toString());
  }

  if (size) {
    irisParams.append('s', size);
  }

  if (quality) {
    irisParams.append('q', quality.toString());
  }

  let originPathname;

  try {
    const { origin, pathname } = new URL(src);

    originPathname = origin + pathname;
  } catch {
    originPathname = CDN_URL + src;
  }

  const irisParamsString = irisParams.toString();
  const computedSrc = originPathname + (irisParamsString === '' ? '' : `?${irisParamsString}`);

  return (
    <>
      <img
        loading={loading}
        src={computedSrc}
        alt={alt}
        height={imgHeight}
        width={imgWidth}
        data-testid="IrisImage"
        {...rest}
      />
      {children?.({ computedSrc })}
    </>
  );
};

export default IrisImage;
