/**
 * Stripe Elements 決済コンポーネント
 *
 * PaymentIntent の client_secret を受け取り、カード入力UIを表示する。
 */
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { loadStripe } from '@stripe/stripe-js';
import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';

const stripePromise = window.confManagerPayment?.stripePublishableKey
	? loadStripe( window.confManagerPayment.stripePublishableKey )
	: null;

function CheckoutForm( { onSuccess, onError } ) {
	const stripe = useStripe();
	const elements = useElements();
	const [ processing, setProcessing ] = useState( false );
	const [ errorMessage, setErrorMessage ] = useState( '' );

	const handleSubmit = async () => {
		if ( ! stripe || ! elements ) {
			return;
		}

		setProcessing( true );
		setErrorMessage( '' );

		const { error, paymentIntent } = await stripe.confirmPayment( {
			elements,
			redirect: 'if_required',
		} );

		if ( error ) {
			setErrorMessage( error.message );
			onError?.( error.message );
			setProcessing( false );
		} else if ( paymentIntent?.status === 'succeeded' ) {
			onSuccess?.();
		} else {
			setProcessing( false );
		}
	};

	return (
		<div className="conf-manager-stripe-form">
			<PaymentElement />

			{ errorMessage && (
				<p className="conf-manager-stripe-error">{ errorMessage }</p>
			) }

			<button
				onClick={ handleSubmit }
				disabled={ ! stripe || processing }
				className="conf-manager-form__submit"
				style={ { marginTop: '16px' } }
			>
				{ processing
					? __( 'Processing payment...', 'conferencemanager' )
					: __( 'Register with Card Payment', 'conferencemanager' ) }
			</button>
		</div>
	);
}

export default function StripePaymentWrapper( { clientSecret, onSuccess, onError } ) {
	if ( ! stripePromise || ! clientSecret ) {
		return null;
	}

	return (
		<Elements stripe={ stripePromise } options={ { clientSecret, locale: 'ja' } }>
			<CheckoutForm onSuccess={ onSuccess } onError={ onError } />
		</Elements>
	);
}
