import React from 'react';
import {
  ActivityIndicator,
  ColorValue,
  Modal,
  SafeAreaView,
  StyleSheet,
  TouchableOpacity,
  View,
  Platform,
} from 'react-native';

import {WebView} from 'react-native-webview';

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

const isAndroid = Platform.OS === 'android';

interface Props {
  closeModal: () => void;
  loadingColor?: ColorValue;
  visible: boolean;
  url: string;
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: StyleGuide.colors.white,
    paddingTop: isAndroid ? 16 : 0,
  },
  centered: {justifyContent: 'center', alignItems: 'center'},
  header: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    flexDirection: 'row-reverse',
  },
  loaderContainer: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: StyleGuide.colors.white,
  },
});

const PromoModal: React.FC<Props> = ({
  closeModal,
  loadingColor,
  url,
  visible,
}: Props) => {
  const [ready, setReady] = React.useState(false);

  const handleLoadEnd = React.useCallback(() => {
    setReady(true);
  }, []);

  return (
    <Modal animationType="slide" visible={visible}>
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity onPress={closeModal}>
            <ClosingCross fill={StyleGuide.colors.closingCross} size={32} />
          </TouchableOpacity>
        </View>
        <WebView
          style={styles.container}
          source={{uri: url}}
          onError={closeModal}
          onHttpError={closeModal}
          onLoad={handleLoadEnd}
        />
        {!ready ? (
          <View style={styles.loaderContainer}>
            <ActivityIndicator
              color={loadingColor || StyleGuide.colors.black}
              size={40}
            />
          </View>
        ) : null}
      </SafeAreaView>
    </Modal>
  );
};

export {PromoModal};
