import React, { useState, useEffect, useRef } from 'react';
import { Helmet } from 'react-helmet';
import { clearUpCopyAndPay, generateOptions, useFetch } from './Helpers';

const ExpressComponent = React.memo((props) => {
	const [checkoutId, setCheckoutId] = useState(null);
	const shippingMethod = useRef(null);
	const containerRef = useRef(null);

	useEffect(() => {
		useFetch('hyperpay_prepare_checkout')
			.get('')
			.then((res) => {
				const id = res.data;
				window.wpwlOptions = generateOptions(props, shippingMethod, id);
				setCheckoutId(id);
			});

		return () => clearUpCopyAndPay();
	}, []);

	useEffect(() => {
		if (!checkoutId || !containerRef.current) {
			return;
		}

		containerRef.current.innerHTML = '';

		const form = document.createElement('form');
		form.className = 'paymentWidgets';
		form.setAttribute('data-brands', props.setting.brands);

		containerRef.current.appendChild(form);
	}, [checkoutId]);

	return (
		<div>
			{checkoutId && (
				<>
					<div ref={containerRef}></div>

					<Helmet>
						<script src={`${props.setting.script_url}${checkoutId}`}></script>
					</Helmet>
				</>
			)}
		</div>
	);
}, () => true);

export default ExpressComponent;