import React, { useState, useEffect } from "react";
import { SvgCssUri } from "react-native-svg";
import { CSSObject } from "styled-components";
import ImageDefault from "assets/images/default.png";
import { Img } from "./styles";

export type ResizeImageTypes = "contain" | "cover" | "center";

export interface IImageProps {
  src: string | number;
  imgWidth?: string;
  imgHeight?: string;
  alt?: string;
  isSvg?: boolean;
  resizeMode?: ResizeImageTypes;
  styles?: CSSObject;
}

export const AtomImage = ({
  src,
  imgWidth = "150px",
  imgHeight = "150px",
  alt = "",
  isSvg = false,
  resizeMode = "contain",
  styles = {},
}: IImageProps) => {
  const [imgSrc, setImgSrc] = useState<any>(src);

  useEffect(() => {
    let imgUri: any = src ? { uri: src } : { uri: ImageDefault };
    imgUri = { uri: imgUri.uri?.testUri ?? imgUri.uri };
    const img = !!src && typeof src === "number" ? src : imgUri;
    setImgSrc(img);
  }, [src]);

  return isSvg && !!src && typeof src === "string" ? (
    <SvgCssUri
      testID="svg-test-id"
      uri={src}
      accessibilityLabel={alt}
      width={imgWidth}
      height={imgHeight}
    />
  ) : (
    <>
      {imgSrc.uri && (
        <Img
          testID="img-test-id"
          resizeMode={resizeMode}
          accessibilityLabel={alt}
          imgWidth={imgWidth}
          imgHeight={imgHeight}
          source={imgSrc}
          styles={styles}
        />
      )}
    </>
  );
};
