import React, { useRef } from 'react';
import { View, DeviceEventEmitter } from 'react-native';
import { DenetWebview } from '@/components/webview';
import { onReplyDialogOpen } from '@/utils/contentInTwitterJS/comment';
import { postRequest } from '@/netWork/request';

interface Props {
	navigation: any;
	route: any;
}

const Comment = (props: Props) => {
	const webRef = useRef({} as any);
	const params = props.route.params.data;
	const uri = `https://mobile.twitter.com/intent/tweet?in_reply_to=${props.route.params.data.tweetId}`;
	const inject = () => {
		webRef.current.injectJavaScript(`
		(${onReplyDialogOpen})();
      true;
    `);
	};

	const fetchAddFinishEvent = () => {
		console.log('fetchAddFinishEvent', params);
		return postRequest('/denet/post/luckdrop/addFinishEvent', {
			params: {
				eventType: params.type,
				luckdropId: params.taskLuckdropId,
			},
		}).catch((e: any) => {
			console.log('fetchAddFinishEvent error', e);
		});
	};

	const onMessageHandle = async (messageData: any) => {
		let { actionType } =
			(messageData.nativeEvent.data &&
				JSON.parse(messageData.nativeEvent.data)) ||
			{};
		console.log('onMessageHandle', actionType);
		switch (actionType) {
			case 'commentSuccess':
				const res = await fetchAddFinishEvent();
				console.log('commentSuccess res....', res);
				DeviceEventEmitter.emit(
					`IFRAME_RED_PACKET_REPLY_CLICK-${params.tweetId}`,
				);
				props.navigation.navigate(
					'Redpack',
					props.route.params.routerData,
				);
				break;
			default:
				break;
		}
	};
	return (
		<View style={{ flex: 1 }}>
			<DenetWebview
				uri={uri}
				onLoadEndHandle={inject}
				onMessageHandle={onMessageHandle}
				refHandle={r => (webRef.current = r)}
			/>
		</View>
	);
};

export default Comment;
