import React from 'react';
import {ActivityIndicator, ColorValue, StyleSheet, View} from 'react-native';

import {WebView} from 'react-native-webview';
import {
  WebViewError,
  WebViewHttpError,
  WebViewErrorEvent,
  WebViewHttpErrorEvent,
  WebViewMessageEvent,
} from 'react-native-webview/lib/WebViewTypes';

import {StyleGuide} from '../lib/utils/styleGuide';

interface Props {
  url: string;
  onBack?: () => void;
  onResult: (result: WebViewResult) => void;
  onError?: (error: WebViewError | WebViewHttpError) => void;
  loadingColor?: ColorValue;
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: StyleGuide.colors.white,
  },
  centered: {justifyContent: 'center', alignItems: 'center'},
  header: {flexDirection: 'row', paddingHorizontal: 12},
  logo: {alignItems: 'center', flex: 1, paddingLeft: 32},
});

export type WebViewResult = 'close' | 'authorized' | 'rejected' | 'expired';

const TabbyPaymentWebView: React.FC<Props> = ({
  url,
  onResult,
  onError,
  loadingColor,
}: Props) => {
  const parseMessage = (msg: WebViewResult) => {
    onResult(msg);
  };

  const onWebViewError = (syntheticEvent: WebViewErrorEvent) => {
    const {nativeEvent} = syntheticEvent;
    if (onError) {
      onError(nativeEvent);
    }
  };

  const onHttpError = (syntheticEvent: WebViewHttpErrorEvent) => {
    const {nativeEvent} = syntheticEvent;
    if (onError) {
      onError(nativeEvent);
    }
  };

  const onMessage = ({nativeEvent: {data}}: WebViewMessageEvent) => {
    const d = data as WebViewResult;
    parseMessage(d);
  };

  return (
    <View style={styles.container}>
      {url ? (
        <WebView
          allowFileAccess
          allowFileAccessFromFileURLs
          allowsLinkPreview
          domStorageEnabled
          style={styles.container}
          source={{uri: url}}
          onError={onWebViewError}
          enableApplePay
          onHttpError={onHttpError}
          onMessage={onMessage}
          mediaCapturePermissionGrantType={'grant'}
        />
      ) : (
        <View style={[styles.centered, styles.container]}>
          <ActivityIndicator
            color={loadingColor || StyleGuide.colors.black}
            size={40}
          />
        </View>
      )}
    </View>
  );
};

export {TabbyPaymentWebView};
