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

import { findPluginByIdentifier } from "@applicaster/zapp-react-native-utils/pluginUtils";
import { usePickFromState } from "@applicaster/zapp-react-native-redux/hooks";
import {
  inflateString,
  objectToReadableString,
} from "@applicaster/zapp-react-native-utils/stringUtils";
import { sessionStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/SessionStorage";

type Props = {
  screenData: ZappEntry;
};

const WEBVIEW_SCREEN_IDENTIFIER = "webview_screen_qb";

export async function inflateUrl(url) {
  if (url.startsWith("mailto")) {
    const storage = await sessionStorage.getAllItems("applicaster.v2");

    const deviceInfo = objectToReadableString({
      "Device Model": storage?.deviceModel,
      "OS Version": storage?.osVersion,
      Platform: storage?.platform,
      Version: storage?.version_name,
      UUID: storage?.uuid,
    });

    return inflateString({
      string: url,
      data: {
        deviceInfo,
      },
    });
  }

  return url;
}

export function LinkHandler(props: Props) {
  const screenData = props?.screenData;
  const { plugins } = usePickFromState(["rivers", "plugins"]);

  const ScreenPlugin = findPluginByIdentifier(
    WEBVIEW_SCREEN_IDENTIFIER,
    plugins
  );

  const Component =
    R.path(["module", "Component"], ScreenPlugin) ||
    R.prop("module", ScreenPlugin) ||
    ScreenPlugin;

  return <Component screenData={screenData} />;
}
