import * as React from "react";
import { logger } from "@applicaster/zapp-react-native-utils/logger";
import { isNil } from "ramda";

import { getImageSize, getDimension } from "./utils";

type Uri = string;

type Dimension = {
  aspectRatio: number;
  width: number;
  height: number;
};

type Action = {
  uri: Uri;
  dimension: Dimension;
};

type State = Record<Uri, Dimension>;

const reducer = (state: State, action: Action): State => {
  const currentDimension = state?.[action.uri];

  if (!isNil(currentDimension)) {
    return state;
  }

  return {
    ...state,
    [action.uri]: action.dimension,
  };
};

const UNDEFINED_DIMENSION = {
  aspectRatio: undefined,
  width: undefined,
  height: undefined,
};

export const useGetImageDimensions = (
  uri: Nullable<string>,
  width: number,
  height: Nullable<number>
) => {
  const [dimensions, dispatch] = React.useReducer(reducer, {
    [uri]: getDimension({ width, height }),
  });

  React.useEffect(() => {
    if (!isNil(uri) && isNil(dimensions[uri])) {
      getImageSize(uri, width, height)
        .then(({ width, height }) => {
          dispatch({
            uri,
            dimension: getDimension({ width, height }),
          });
        })
        .catch((e) => {
          logger.error({
            message: "Cell failed to load secondary image by url",
            data: { url: uri, error: e.message },
          });

          dispatch({
            uri,
            dimension: UNDEFINED_DIMENSION,
          });
        });
    }
  }, [uri, dimensions]);

  return dimensions[uri];
};
