import * as React from "react";
import * as R from "ramda";

import { isTV } from "@applicaster/zapp-react-native-utils/reactUtils";
import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions";
import { extractAsset } from "./utils";

type Return = { uri: string } | null;

export const useImageSource = ({ uri, entry, otherProps }): Return => {
  const uriContext = R.path(["source", "context"], otherProps);
  const uriState = R.path(["state"], otherProps);

  const action = useActions(uriContext);

  const initialEntryState = action?.initialEntryState?.(entry);

  const [entryStateLocal, setEntryStateLocal] =
    React.useState(initialEntryState);

  React.useEffect(() => {
    return action?.addListeners?.(({ entryState, entry: actionEntry }) => {
      if (entry.id === actionEntry.id) {
        setEntryStateLocal(entryState);
      }
    });
  }, []);

  if (uriContext && uriState && action) {
    return extractAsset(!isTV(), entryStateLocal.asset, uriState);
  }

  if (uri) {
    return { uri };
  }

  const uriFromSource = R.path(["source", "uri"], otherProps);

  if (uriFromSource) {
    return { uri: uriFromSource };
  }

  return null;
};

const getSource = (uri, showDefault, placeholderImage, otherProps) => {
  const placeholderName = placeholderImage || "";

  const defaultPath = {
    uri: placeholderName,
  };

  if (showDefault) return defaultPath;

  if (uri) {
    return { uri };
  }

  const uriFromSource = R.path(["source", "uri"], otherProps);

  if (uriFromSource) {
    return { uri: uriFromSource };
  }

  return defaultPath;
};

export const useImageSourceWithDefault = ({
  uri,
  entry,
  showDefault,
  placeholderImage,
  otherProps,
}): Return => {
  const uriContext = R.path(["source", "context"], otherProps);
  const uriState = R.path(["state"], otherProps);

  const action = useActions(uriContext);

  const initialEntryState = action?.initialEntryState?.(entry);

  const [entryStateLocal, setEntryStateLocal] =
    React.useState(initialEntryState);

  React.useEffect(() => {
    return action?.addListeners?.(({ entryState, entry: actionEntry }) => {
      if (entry.id === actionEntry.id) {
        setEntryStateLocal(entryState);
      }
    });
  }, []);

  if (uriContext && uriState && action) {
    return extractAsset(!isTV(), entryStateLocal.asset, uriState);
  }

  return getSource(uri, showDefault, placeholderImage, otherProps);
};
