import { getSetting } from "@woocommerce/settings";
import { decodeEntities } from "@wordpress/html-entities";
import { __ } from "@wordpress/i18n";
import { registerPaymentMethod } from "@woocommerce/blocks-registry";

const ccMethod = 'sibs_stg_cc';
const ccData = getSetting(ccMethod + '_data', null);

const Label = () => {
	var title = decodeEntities(ccData?.title);
	const logos = ccData?.logos;
	const images = [];

	logos.forEach((url) => {
		images.push(
			<img
				src={url}
				style={{ display: "inline", paddingRight: "5px" }}
			/>,
		);
	});

	return (
		<div className="wc-block-components-payment-method-label wc-block-components-payment-method-label--with-icon">
			{" "}
			{images} <span> {title} </span>
		</div>
	);
};

const Content = (props) => {
	const [sibs_stg_oneclick_customer_acceptor, setChecked] = React.useState("");
	const oneclicklabel = ccData?.checkoutLabel || "";
	const { eventRegistration, emitResponse } = props;
	const { onPaymentProcessing } = eventRegistration;
	const handleChange = (event) => {
		setChecked(event.target.checked);
	};

	if (ccData?.checkoutLabel) {
		React.useEffect(() => {
			const customerAcceptor = onPaymentProcessing(async () => {
				return {
					type: emitResponse.responseTypes.SUCCESS,
					meta: {
						paymentMethodData: {
							sibs_stg_oneclick_customer_acceptor,
						},
					},
				};
			});
			return () => {
				customerAcceptor();
			};
		}, [
			emitResponse.responseTypes.ERROR,
			emitResponse.responseTypes.SUCCESS,
			onPaymentProcessing,
			sibs_stg_oneclick_customer_acceptor,
		]);
		return (
			<div style={{ display: "flex", alignItems: "flex-start" }}>
				<input
					type="checkbox"
					name="sibs_stg_oneclick_customer_acceptor"
					className="wc-block-components-checkbox__input"
					onChange={handleChange}
					checked={
						sibs_stg_oneclick_customer_acceptor === false
							? true
							: sibs_stg_oneclick_customer_acceptor
					}
					id="sibs_stg_oneclick_customer_acceptor"
					style={{ display: "inline", marginRight: "5px" }}
				/>
				<label
					htmlFor="sibs_stg_oneclick_customer_acceptor"
					className="wc-block-components-checkbox__label"
				>
					<span dangerouslySetInnerHTML={{ __html: oneclicklabel }} />
				</label>
			</div>
		);
	} else {
		return "";
	}
};

registerPaymentMethod({
	name: ccMethod,
	label: <Label />,
	ariaLabel: __("SIBS payment method", "sibs-woo-stg"),
	canMakePayment: () => true,
	content: <Content />,
	edit: <Content />,
	supports: {
		features: ccData?.supports ?? [],
	},
});
