import React, { useState, useRef, useCallback } from 'react';
import { Pressable, Modal, View, StyleSheet, Text, Image } from 'react-native';
import { WebView } from 'react-native-webview';
import useChicoLogger from './useChicoLogger';
import ChicoLogo from '../assets/icon.png';

interface Props {
  client: string;
  chicoToken: string;
  callToAction?: string;
  onClose?: (result: 'success' | 'fail') => void;
}

const ConnectAccountsButton = ({
  client,
  chicoToken,
  callToAction = 'Connect with Chico',
  onClose,
}: Props) => {
  const [isWebViewOpen, setIsWebviewOpen] = useState(false);
  useChicoLogger(client, chicoToken);

  const buildURL = (token: string, customerName: string) =>
    `https://connector.chico.ai/?userId=${token}&client=${customerName}`;
  const onURLChangeHandler = (url: string) => {
    if (url.endsWith('/exit')) {
      // Close Webview
      onClose && onClose('success');
      setIsWebviewOpen(false);
    }
  };

  const webview = useRef<WebView>(null);
  const onAndroidBackPress = useCallback((): boolean => {
    if (webview.current) {
      setIsWebviewOpen(false);
      onClose && onClose('success');
      return true; // prevent default behavior (exit app)
    }
    return false;
  }, [onClose]);

  return (
    <View style={styles.container}>
      <Pressable
        onPress={() => {
          setIsWebviewOpen(true);
        }}
        style={styles.button}
      >
        <Image style={styles.tinyLogo} source={ChicoLogo} />
        <Text style={styles.text}>{callToAction}</Text>
      </Pressable>
      <Modal visible={isWebViewOpen} onRequestClose={onAndroidBackPress}>
        <WebView
          ref={webview}
          injectedJavaScript={`
            (function() {
              function wrap(fn) {
                return function wrapper() {
                  var res = fn.apply(this, arguments);
                  window.ReactNativeWebView.postMessage(window.location.href);
                  return res;
                }
              }
              history.pushState = wrap(history.pushState);
              history.replaceState = wrap(history.replaceState);
              window.addEventListener('popstate', function() {
                window.ReactNativeWebView.postMessage(window.location.href);
              });
            })();
            true;
          `}
          style={styles.webview}
          source={{ uri: buildURL(chicoToken, client) }}
          onMessage={(event) => {
            onURLChangeHandler(event.nativeEvent.data);
          }}
        />
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    flex: 1,
  },
  button: {
    flexDirection: 'row',
    textAlign: 'center',
    justifyContent: 'flex-start',
    paddingVertical: 16,
    paddingHorizontal: 16,
    borderRadius: 5,
    elevation: 3,
    backgroundColor: '#fff',
    marginHorizontal: 16,
  },
  text: {
    fontSize: 16,
    fontWeight: '600',
    letterSpacing: 0.25,
    color: '#777',
    alignSelf: 'center',
  },
  tinyLogo: {
    width: 24,
    height: 24,
    marginRight: 16,
  },
  webview: {
    flex: 1,
    marginTop: 40,
  },
});

export { ConnectAccountsButton };
