import React from 'react';
import {View, StyleSheet} from 'react-native';
import {WebView} from 'react-native-webview';
import {WebViewMessageEvent} from 'react-native-webview/lib/WebViewTypes';
import {Currency, Lang} from '../constants/payment';
import {Tabby} from '../lib/TabbyRN';
import {PromoModal} from './PromoModal';

interface Props {
  price: string;
  currency: Currency;
  lang: Lang;
  merchantCode: string;
  publicKey: string;
  installmentsCount: number;
}

enum JSEventType {
  onChangeDimensions = 'onChangeDimensions',
  onLearnMoreClicked = 'onLearnMoreClicked',
}

interface JSEventBase {
  type: JSEventType;
}

type DimensionChangeEvent = JSEventBase & {
  type: JSEventType.onChangeDimensions;
  data: {width: number; height: number};
};

type LearnMoreClickedEvent = JSEventBase & {
  type: JSEventType.onLearnMoreClicked;
  url: string;
  data: string;
};

const styles = StyleSheet.create({f1: {flex: 1}});

const TabbyProductPageWidget: React.FC<Props> = ({
  currency,
  lang,
  price,
  publicKey,
  merchantCode,
  installmentsCount = 4,
}: Props) => {
  const [height, setHeight] = React.useState(90);
  const [modalUrl, setModalUrl] = React.useState<string>('');
  const uri = React.useMemo(() => {
    return [
      `${Tabby.widgetsUrl}`,
      `?price=${price}`,
      `&currency=${currency}`,
      `&lang=${lang}`,
      `&publicKey=${publicKey}`,
      `&merchantCode=${merchantCode}`,
      `&installmentsCount=${installmentsCount}`,
    ].join('');
  }, [currency, price, lang, publicKey, merchantCode, installmentsCount]);

  const onMessage = React.useCallback(
    ({nativeEvent: {data}}: WebViewMessageEvent) => {
      const event: JSEventBase = JSON.parse(data);
      console.log(event);
      if (event.type === JSEventType.onChangeDimensions) {
        const {data: eventData} = event as DimensionChangeEvent;
        if (eventData && eventData.height) {
          setHeight(eventData.height);
        }
        return;
      }
      if (event.type === JSEventType.onLearnMoreClicked) {
        const {data: eventData, url} = event as LearnMoreClickedEvent;
        setModalUrl(`${url}&initializationData=${eventData}`);
      }
    },
    [],
  );

  const closeModal = React.useCallback(() => {
    setModalUrl('');
  }, []);

  return (
    <>
      <View style={{height, backgroundColor: 'transparent'}}>
        <WebView
          source={{uri}}
          onMessage={onMessage}
          style={[styles.f1, {backgroundColor: 'transparent'}]}
        />
      </View>
      <PromoModal visible={!!modalUrl} closeModal={closeModal} url={modalUrl} />
    </>
  );
};

export {TabbyProductPageWidget};
