import { getSetting } from "@woocommerce/settings";
import { decodeEntities } from "@wordpress/html-entities";
import { __ } from "@wordpress/i18n";
import { registerPaymentMethod } from "@woocommerce/blocks-registry";
import { useState, useEffect } from "@wordpress/element";
// import { useSibsCheckout } from "../hooks/useSibsCheckout";

const METHOD = "sibs_stg_cc";
const SETTINGS_KEY = `${METHOD}_data`;

const data = getSetting(SETTINGS_KEY) || {};
// const checkoutEndpoint = data?.checkoutEndpoint;

/**
 * Label
 */
const Label = () => {
	if (!data) return null;

	const title = decodeEntities(data?.title || "");
	const logos = data?.logos || [];

	return (
		<div className="wc-block-components-payment-method-label wc-block-components-payment-method-label--with-icon">
			{logos.map((url, index) => (
				<img
					key={index}
					src={url}
					style={{ display: "inline", paddingRight: "5px" }}
					alt=""
				/>
			))}
			<span>{title}</span>
		</div>
	);
};

/**
 * Content
 */
const Content = ({ eventRegistration, emitResponse }) => {
	const [checked, setChecked] = useState(false);

	const description = decodeEntities(data?.description ?? "");
	const checkoutLabel = data?.checkoutLabel;

	/**
	 * ✅ VALIDATION (before Place Order)
	 */
	useEffect(() => {
		const unsubscribe = eventRegistration.onPaymentSetup(() => {
			// If no checkbox required → always valid
			if (!checkoutLabel) {
				return true;
			}

			// If required but not checked → block checkout
			/*if (!checked) {
				return {
					type: emitResponse.responseTypes.ERROR,
					message: __(
						"You must accept this option to continue.",
						data?.translation
					),
				};
			}*/

			return true;
		});

		return () => unsubscribe();
	}, [checked, checkoutLabel]);

	/**
	 * ✅ PROCESSING (after Place Order)
	 */
	/*useSibsCheckout({
		method: METHOD,
		endpoint: checkoutEndpoint,
		eventRegistration,
		emitResponse,
		data,
		enabled: true,
		getPayload: () => ({
			requires_acceptance: !!checkoutLabel,
		}),
	});*/

	useEffect(() => {
		const unsubscribe = eventRegistration.onPaymentProcessing(() => {
			console.log('checked: ' + checked)
			return {
				type: emitResponse.responseTypes.SUCCESS,
				meta: {
					paymentMethodData: {
						sibs_stg_oneclick_customer_acceptor: checked,
					},
				},
			};
		});

		return () => unsubscribe();
	}, [checked]);

	return (
		<div>
			{/* DESCRIPTION */}
			{description && (
				<div
					className="sibs-cc-description"
					dangerouslySetInnerHTML={{ __html: description }}
					style={{ marginBottom: "10px" }}
				/>
			)}

			{/* CHECKBOX (only if exists) */}
			{checkoutLabel && (
				<div style={{ display: "flex", alignItems: "flex-start" }}>
					<input
						type="checkbox"
						className="wc-block-components-checkbox__input"
						onChange={(e) => setChecked(e.target.checked)}
						checked={checked}
						id="sibs_stg_oneclick_customer_acceptor"
						style={{ marginRight: "5px" }}
					/>

					<label
						htmlFor="sibs_stg_oneclick_customer_acceptor"
						className="wc-block-components-checkbox__label"
					>
						<span
							dangerouslySetInnerHTML={{
								__html: checkoutLabel,
							}}
						/>
					</label>
				</div>
			)}
		</div>
	);
};

/**
 * Register payment method
 */
registerPaymentMethod({
	name: METHOD,
	label: <Label />,
	ariaLabel: __("SIBS payment method", data?.translation),
	canMakePayment: () => true,
	content: <Content />,
	edit: <Content />,
	supports: {
		features: data?.supports ?? [],
	},
});