import * as React from "react";
import { StyleSheet, Image } from "react-native";

/**
 * This import is used by the Svelte SDK. Do not remove.
 */

export interface ImgProps {
  attributes?: any;
  imgSrc?: string; // TODO(misko): I think this is unused
  image?: string;
  altText?: string;
  backgroundSize?: "cover" | "contain";
  backgroundPosition?:
    | "center"
    | "top"
    | "left"
    | "right"
    | "bottom"
    | "top left"
    | "top right"
    | "bottom left"
    | "bottom right";
  aspectRatio?: number;
  title?: string;
}

import { isEditing } from "../../functions/is-editing";
import { filterAttrs } from "../helpers";
import { getSrcSet } from "../image/image.helpers";
import { getClassPropName } from "../../functions/get-class-prop-name";

function ImgComponent(props: ImgProps) {
  function srcSetToUse() {
    const url = props.imgSrc || props.image;
    if (!url || typeof url !== "string") {
      return undefined;
    }

    // We can auto add srcset for cdn.builder.io images
    if (!url.match(/builder\.io/)) {
      return undefined;
    }
    return getSrcSet(url);
  }

  function imgAttrs() {
    const attrs = {
      ...props.attributes,
      ...{},
      [getClassPropName()]: `builder-raw-img ${
        props.attributes[getClassPropName()] || ""
      }`,
    } as Record<string, any>;
    delete attrs.style;
    return attrs;
  }

  return (
    <Image
      loading="lazy"
      key={(isEditing() && props.imgSrc) || "default-key"}
      alt={props.altText}
      title={props.title}
      source={{ uri: props.imgSrc || props.image }}
      {...imgAttrs()}
      style={{
        objectFit: props.backgroundSize || "cover",
        objectPosition: props.backgroundPosition || "center",
        aspectRatio: props.aspectRatio || undefined,
        ...(props.attributes?.style || {}),
      }}
    />
  );
}

export default ImgComponent;
