/**
 * PaymentCore: orchestrator that fetches payment providers, shows loading/processing
 * states, and delegates to PaymentFactory.
 */
import { useState, useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Card, CardBody, Flex, Notice } from '@wordpress/components';
import { Spinner } from '@woocommerce/components';
import apiFetch from '@wordpress/api-fetch';
import type {
	PaymentProviders,
	GenericPaymentResponse,
	GenericErrorResponse,
} from '../../../types';
import PaymentFactory from './payment-factory';
import { PaymentOrderResponse } from '../../../types/payment';
import { captureException } from '../../sentry';
import { getCourierLogo } from '../../utils';

interface PaymentCoreProps {
	paymentOrder: PaymentOrderResponse;
	onSuccess: (response: GenericPaymentResponse, paymentOrder: PaymentOrderResponse) => void;
}

export default function PaymentCore({
	paymentOrder,
	onSuccess,
}: PaymentCoreProps) {
	const [paying, setPaying] = useState(false);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState<string | null>(null);
	const [providers, setProviders] = useState<PaymentProviders | null>(null);

	const { orderId, hash } = paymentOrder.orderResult;

	useEffect(() => {
		let cancelled = false;

		const fetchProviders = async () => {
			setLoading(true);
			setError(null);
			try {
				const data = (await apiFetch({
					path: '/parcel2go-shipping/v1/payment/providers',
					method: 'POST',
					data: { orderId, hash },
				})) as {
					success: boolean;
					result: PaymentProviders;
					validationErrors: GenericErrorResponse[] | null;
				};

				if (!cancelled && data.success && data.result) {
					setProviders(data.result);
				}
			} catch (err: unknown) {
				captureException(
					err instanceof Error ? err : new Error(String(err))
				);
				if (
					!cancelled &&
					err &&
					typeof err === 'object' &&
					'message' in err
				) {
					setError(String((err as { message: string }).message));
				} else {
					setError(
						__(
							'Failed to load payment options.',
							'parcel2go-shipping'
						)
					);
				}
			} finally {
				setLoading(false);
			}
		};

		fetchProviders();
		return () => {
			cancelled = true;
		};
	}, [orderId, hash]);

	if (error) {
		return (
			<Notice status="error" isDismissible={false}>
				{error}
			</Notice>
		);
	}

	if (loading || !providers) {
		return (
			<Flex
				direction="column"
				gap={3}
				align="center"
				justify="center"
				style={{ padding: 24 }}
			>
				<Spinner />
				<span style={{ color: '#757575' }}>
					{__('Loading payment options...', 'parcel2go-shipping')}
				</span>
			</Flex>
		);
	}

	const p2gLogo = getCourierLogo('p2g');

	return (
		<Flex direction="column" gap={3}>
			{/* Price summary */}
			<Card size="small" style={{ marginBottom: 16 }}>
				<CardBody>
					<Flex direction="column" gap={3}>
						<Flex
							gap={2}
							justify="space-between"
							align="flex-start"
						>
							<Flex
								direction="column"
								justify="flex-start"
								gap={1}
							>
								<img
									src={p2gLogo}
									alt="Parcel2Go"
									style={{ width: '120px' }}
								/>
								<span
									style={{ fontSize: 13, color: '#757575' }}
								>
									{__(
										'Secure payment powered by Parcel2Go',
										'parcel2go-shipping'
									)}
								</span>
							</Flex>
							<Flex
								direction="column"
								gap={0}
								style={{ textAlign: 'right' }}
							>
								<span
									style={{ fontSize: 12, color: '#757575' }}
								>
									{__('Net:', 'parcel2go-shipping')} £
									{(providers.netTotalInUnits / 100).toFixed(
										2
									)}
									{' + '}
									{__('VAT:', 'parcel2go-shipping')} £
									{(providers.vatTotalInUnits / 100).toFixed(
										2
									)}
								</span>
								<span
									style={{
										fontSize: 18,
										fontWeight: 600,
										color: '#00a32a',
									}}
								>
									£{(providers.totalInUnits / 100).toFixed(2)}
								</span>
							</Flex>
						</Flex>
						<span style={{ fontSize: 13, color: '#757575' }}>
							{__(
								'Company Number: 02591405 | VAT Number: 597 8491 61',
								'parcel2go-shipping'
							)}
						</span>
					</Flex>
				</CardBody>
			</Card>

			{/* Processing state */}
			{paying && (
				<Flex
					direction="column"
					gap={3}
					align="center"
					style={{ padding: 24 }}
				>
					<Spinner />
					<span style={{ fontWeight: 600 }}>
						{__('Processing payment...', 'parcel2go-shipping')}
					</span>
					<span style={{ fontSize: 13, color: '#757575' }}>
						{__(
							'Please do not close this page or navigate away.',
							'parcel2go-shipping'
						)}
					</span>
				</Flex>
			)}

			{/* Payment options (hidden while processing) */}
			<div
				style={{
					maxHeight: paying ? 0 : 1000,
					overflow: 'hidden',
					pointerEvents: paying ? 'none' : 'auto',
					transition: 'max-height 0.3s ease-in-out',
				}}
			>
				<PaymentFactory
					paymentOrder={paymentOrder}
					paymentProviders={providers}
					onSuccess={onSuccess}
				/>
			</div>
		</Flex>
	);
}
