import * as React from "react";
import { isNil } from "ramda";
import { ImageStyle, View } from "react-native";
import {
  FIT_POSITION,
  IMAGE_SIZING_FIT,
  IMAGE_SIZING_FILL,
} from "@applicaster/zapp-react-native-utils/manifestUtils/secondaryImage";
import { QBImage as Image } from "@applicaster/zapp-react-native-ui-components/Components/Image";

import { useGetImageDimensions } from "./hooks";
import {
  DisplayMode,
  getStyle,
  isDisplayModeFixed,
  isImageSizingFit,
} from "./utils";
import { withAsyncRenderHOC } from "../../hoc/withAsyncRender";

interface Props {
  displayMode: DisplayMode;
  uri: Nullable<string>;
  style: ImageStyle;
  imageSizing: typeof IMAGE_SIZING_FIT | typeof IMAGE_SIZING_FILL;
  fitPosition: typeof FIT_POSITION;
  fixedWidth: number;
  fixedHeight: number;
  onAsyncRender: () => void;
}

const SecondaryImageComponent = (props: Props) => {
  const {
    uri,
    style,
    displayMode,
    imageSizing,
    fitPosition,
    fixedHeight,
    fixedWidth,
    onAsyncRender,
  } = props;

  const imageDimension = useGetImageDimensions(
    uri,
    style.width as number,
    isImageSizingFit(imageSizing) ? undefined : (style.height as number)
  );

  const containerHeight = isDisplayModeFixed(displayMode)
    ? fixedHeight
    : imageDimension?.height;

  const containerWidth = isDisplayModeFixed(displayMode)
    ? fixedWidth
    : style?.width;

  if (isNil(imageDimension?.aspectRatio)) {
    return null;
  }

  return (
    <View style={style} onLayout={onAsyncRender}>
      <Image
        {...props}
        source={{ uri }}
        style={{
          ...getStyle({
            imageSizing,
            fitPosition,
            displayMode,
            imageDimension,
            containerHeight,
            containerWidth,
          }),
          borderRadius: style.borderRadius,
          aspectRatio: imageDimension.aspectRatio,
        }}
      />
    </View>
  );
};

export const SecondaryImage = withAsyncRenderHOC(SecondaryImageComponent);
