import {useMemo} from 'react';
import RNWebView, {
  WebViewProps,
  WebViewMessageEvent as TWebViewMessageEvent,
  WebViewNavigation as TWebViewNavigation,
} from 'react-native-webview';
import {WebViewOpenWindowEvent as TWebViewOpenWindowEvent} from 'react-native-webview/lib/WebViewTypes';
import {useTheme} from '@shared/theme';

/** Restrict WebView to HTTPS and app schemes; prevents loading arbitrary file:// or user-controlled content */
const SECURE_ORIGIN_WHITELIST = [
  'https://*',
  'http://localhost*',
  'humand://*',
];

export type WebViewMessageEvent = TWebViewMessageEvent;
export type WebViewNavigation = TWebViewNavigation;
export type WebViewOpenWindowEvent = TWebViewOpenWindowEvent;

export interface WebViewComponentProps extends WebViewProps {
  ref?: React.Ref<RNWebView>;
  injectTheme?: boolean;
}

export function WebView({
  ref,
  originWhitelist = [],
  allowFileAccess = false,
  allowUniversalAccessFromFileURLs = false,
  source,
  injectTheme = true,
  ...props
}: WebViewComponentProps): React.ReactElement {
  const {isDarkMode} = useTheme();

  const processedSource = useMemo(() => {
    if (
      !injectTheme ||
      !source ||
      typeof source === 'number' ||
      !('uri' in source) ||
      !source.uri
    ) {
      return source;
    }
    const separator = source.uri.includes('?') ? '&' : '?';
    return {
      ...source,
      uri: `${source.uri}${separator}theme=${isDarkMode ? 'dark' : 'light'}`,
    };
  }, [source, isDarkMode, injectTheme]);

  return (
    <RNWebView
      ref={ref}
      {...props}
      source={processedSource}
      originWhitelist={[...SECURE_ORIGIN_WHITELIST, ...originWhitelist]}
      allowFileAccess={allowFileAccess}
      allowUniversalAccessFromFileURLs={allowUniversalAccessFromFileURLs}
      webviewDebuggingEnabled={__DEV__}
    />
  );
}

export interface WebViewRef extends React.ComponentRef<typeof RNWebView> {}
