import React, {useCallback, useMemo, useRef, useState} from 'react';
import {
  CustomRendererProps,
  TBlock,
  domNodeToHTMLString,
} from 'react-native-render-html';
import {ImageModal} from '@components/_core/Image';
import {
  WebView,
  WebViewRef,
  WebViewMessageEvent,
  WebViewNavigation,
} from '@components/_core/WebView';
import {openUrlFromApp} from '@shared/utils';

import {getWebviewHtml} from './utils';
import {
  POST_EVENT_SEPARATOR,
  POST_MESSAGE_SCRIPT,
  WEBVIEW_EVENTS,
} from './constants';
import {styles} from './styles';

function CustomTableRenderer(props: CustomRendererProps<TBlock>) {
  const webViewRef = useRef<Nullable<WebViewRef>>(null);
  const html = domNodeToHTMLString(props.tnode.domNode);
  const [tableImageUrl, setTableImageUrl] = useState('');
  const [tableHeight, setTableHeight] = useState(0);

  const onImageZoomClose = useCallback(() => {
    setTableImageUrl('');
  }, []);

  const source = useMemo(() => ({html: getWebviewHtml(html)}), [html]);

  const onTableWebViewMessage = useCallback((event: WebViewMessageEvent) => {
    const dataSplitted = event.nativeEvent.data.split(POST_EVENT_SEPARATOR);

    if (dataSplitted.length === 2) {
      const eventName = dataSplitted[0];
      const eventData = dataSplitted[1];

      switch (eventName) {
        case WEBVIEW_EVENTS.IMG_CLICK:
          setTableImageUrl(eventData);
          break;
        case WEBVIEW_EVENTS.TABLE_RENDER:
          setTableHeight(Number(eventData));
          break;
      }
    }
  }, []);

  const onNavigationStateChange = useCallback((event: WebViewNavigation) => {
    if (event.url !== 'about:blank') {
      webViewRef.current?.stopLoading();
      openUrlFromApp(event.url);
    }
  }, []);

  return (
    <>
      <WebView
        ref={webViewRef}
        source={source}
        bounces={false}
        injectedJavaScript={POST_MESSAGE_SCRIPT}
        onMessage={onTableWebViewMessage}
        onNavigationStateChange={onNavigationStateChange}
        allowsLinkPreview={false}
        style={[styles.webView, {height: tableHeight}]}
      />
      <ImageModal
        showZoom={!!tableImageUrl}
        source={{uri: tableImageUrl}}
        onClose={onImageZoomClose}
      />
    </>
  );
}

export default CustomTableRenderer;
