import * as React from "react";
import * as R from "ramda";
import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions";
import { useIsRTL } from "@applicaster/zapp-react-native-utils/localizationUtils";
import { getXray } from "@applicaster/zapp-react-native-utils/logger";

const { Logger } = getXray();

const logger = new Logger(
  "plugin",
  "plugins/navigation-action|plugins/local-storage-favourites-action"
);

const firstEnglishWordRegex = /(^[a-zA-Z]+)/;

const extractLabel = (label, key): string => {
  if (R.is(String, label)) {
    return label;
  }

  return R.pathOr("", [key], label);
};

// if the app is RTL and the first word is english we wrap this word in the unicode to force the RTL alignment
// https://stackoverflow.com/a/48788634
const prepareHebrewText = (label: string, isRTL: boolean): string => {
  if (isRTL && label && firstEnglishWordRegex.test(label)) {
    const unicodeWrapPattern = "\u200f$1\u202c";

    return label.replace(firstEnglishWordRegex, unicodeWrapPattern);
  }

  return label;
};

export const useTextLabel = ({ label, entry }): string => {
  const context = R.path(["context"], label);
  const name = R.path(["name"], label);
  const isRTL = useIsRTL();

  const action = useActions(context);

  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 (context && name && action) {
    return prepareHebrewText(extractLabel(entryStateLocal.label, name), isRTL);
  }

  if (R.is(Object, label) && R.isNil(entryStateLocal)) {
    // fallback to empty string
    const errorMessage = `Cannot resolve label for ${context} plugin - please upgrade to latest version`;

    logger.warning({
      message: errorMessage,
      data: { context },
    });

    return prepareHebrewText(R.pathOr("", ["name"], label), isRTL);
  }

  return prepareHebrewText(label, isRTL);
};

export const withFocusedStyles = ({ style, otherProps }) => {
  const state = R.path(["state"], otherProps);

  if (R.isNil(state)) {
    return style;
  }

  if (state === "focused") {
    return { ...style, ...otherProps.focusedStyles };
  }

  return { ...style, ...otherProps.normalStyles };
};
