import React from "react";
import { View } from "react-native";
import { QBImage } from "@applicaster/zapp-react-native-ui-components/Components";

export type ItemIconProps = {
  width: number;
  height: number;
  asset?: string | string[] | CellActionAssetComponent;
  flavour?: "flavour_1" | "flavour_2";
  marginTop: number;
  marginBottom: number;
  marginLeft: number;
  marginRight: number;
};

function isImageAsset(asset) {
  return typeof asset === "string" || Array.isArray(asset);
}

function getImageAsset(asset, flavour) {
  if (typeof asset === "string") return asset;

  if (flavour) {
    const flavourIndex = Number(flavour.replace("flavour_", ""));
    if (flavourIndex > -1) return asset?.[flavourIndex - 1];
  }

  return asset?.[0];
}

export function ItemIcon(props: ItemIconProps) {
  const { width, height, asset, flavour, ...styles } = props;

  if (isImageAsset(asset)) {
    const imageAsset = getImageAsset(asset, flavour);

    return (
      <View style={styles}>
        <QBImage
          fadeDuration={0}
          source={{ uri: imageAsset }}
          style={{ width, height }}
        />
      </View>
    );
  }

  const AssetComponent = asset as CellActionAssetComponent;

  return (
    <View style={styles}>
      <AssetComponent
        width={width}
        height={height}
        style={styles}
        flavour={flavour}
      />
    </View>
  );
}
