import { __ } from '@wordpress/i18n';
import { Flex, Modal, Notice, Spinner } from '@wordpress/components';
import { GenericPaymentResponse, PaymentOrderResponse } from 'types/payment';
import { useEffect, useState } from 'react';
import apiFetch from '@wordpress/api-fetch';
import { GenericErrorResponse } from 'types/price';
import { addBreadcrumb, captureException } from '../../shared/sentry';

interface LoadingPrepayPaymentProps {
	prepayPaymentOrder: PaymentOrderResponse;
	onRequestClose: () => void;
	onPaymentSuccess: (response: GenericPaymentResponse) => void;
	onPayingChange: (paying: boolean) => void;
}

const LoadingPrepayPayment = ({
	onRequestClose,
	prepayPaymentOrder,
	onPaymentSuccess,
	onPayingChange,
}: LoadingPrepayPaymentProps) => {
	const [error, setError] = useState<string | null>(null);
	const { orderId, hash } = prepayPaymentOrder.orderResult;

	useEffect(() => {
		const processPayment = async () => {
			try {
				const response = (await apiFetch({
					path: '/parcel2go-shipping/v1/payment/prepay',
					method: 'POST',
					data: { orderId, hash },
				})) as {
					success: boolean;
					result: GenericPaymentResponse;
					validationErrors: GenericErrorResponse[] | null;
				};

				if (response.success && response.result.completeHash) {
					onPaymentSuccess(response.result);
				} else if (response.validationErrors?.length > 0) {
					setError(response.validationErrors?.[0]?.detail || '');
				} else {
					setError(
						__('PrePay payment failed.', 'parcel2go-shipping')
					);
					captureException(
						new Error(
							'An unexpected error occurred while processing payment. Please try again.'
						)
					);
					addBreadcrumb(
						'Prepay payment error',
						{
							error: 'An unexpected error occurred while processing payment. Please try again.',
						},
						'payment'
					);
				}
			} catch (err: unknown) {
				captureException(
					err instanceof Error ? err : new Error(String(err))
				);
				const msg =
					err && typeof err === 'object' && 'message' in err
						? String((err as { message: string }).message)
						: __('PrePay payment failed.', 'parcel2go-shipping');
				setError(msg);
			} finally {
				onPayingChange(false);
			}
		};
		processPayment();
	}, []);

	return (
		<Modal
			size="large"
			title={__('Confirm Payment', 'parcel2go-shipping')}
			onRequestClose={onRequestClose}
			isDismissible={true}
			aria-describedby={__('Payment modal', 'parcel2go-shipping')}
			shouldCloseOnClickOutside={false}
		>
			<Flex
				direction="column"
				gap={3}
				align="center"
				justify="center"
				style={{ padding: 24 }}
			>
				{error ? (
					<Notice status="error" isDismissible={false}>
						{error}
					</Notice>
				) : (
                    <Flex gap={3} align="center" justify="center" direction="column">
						<Spinner />
						<span style={{ color: '#757575' }}>
							{__(
								'Processing payment, Please wait...',
								'parcel2go-shipping'
							)}
						</span>
                    </Flex>
				)}
			</Flex>
		</Modal>
	);
};

export default LoadingPrepayPayment;
