/**
 * Order complete / fulfilled view – design aligned with success screen:
 * optional P2G logo, centered title, success message, and action buttons.
 * P2G logo only appears when the order has p2g meta (shipped with Parcel2Go).
 */
import { __ } from '@wordpress/i18n';
import {
	Flex,
	FlexItem,
	Button,
	ButtonGroup,
	Spinner,
	Card,
	CardBody,
} from '@wordpress/components';
import { download, help } from '@wordpress/icons';
import type { Order } from '../../types';
import { getCourierLogo } from '../../shared/utils/getAsset';
import { getLandingPageUrl } from '../../shared/utils';
import { useLabelDownload, useShippingLabelReady } from '../../shared/hooks';

const P2G_HELP_URL =
	'https://www.parcel2go.com/help-centre/parcels/question/general/how-do-i-contact-parcel2go';

export interface OrderCompleteViewProps {
	order: Order;
	orderLabel: string;
	onBack: () => void;
	isFulfilled: boolean;
	p2gOrderLineIds?: string[];
	/** Booking in this session returned a label hash (order refetch may be stale). */
	labelHashSavedThisSession?: boolean;
}

export default function OrderCompleteView({
	order,
	orderLabel,
	onBack,
	isFulfilled,
	p2gOrderLineIds = [],
	labelHashSavedThisSession = false,
}: OrderCompleteViewProps) {
	const hasParcel2GoBooking = Boolean(order.p2g?.orderId);
	const p2gLogo = hasParcel2GoBooking ? getCourierLogo('p2g') : undefined;
	const transactionId = String(order.p2g?.orderId ?? '').replace(/^P2G/i, '');
	const displayOrderLineIds = (
		p2gOrderLineIds.length > 0
			? p2gOrderLineIds
			: (order.p2g?.orderLineIds ?? [])
	)
		.map((orderLineId) => String(orderLineId).trim())
		.filter(Boolean)
		.map((orderLineId) =>
			/^P2G/i.test(orderLineId) ? orderLineId : `P2G${orderLineId}`
		);
	const { showLabelDownload, isResolvingLabel } = useShippingLabelReady(
		order.id,
		{
			labelHashPresent:
				order.p2g?.hasLabelHash === true || labelHashSavedThisSession,
			shouldFetchLabelFromApi:
				!labelHashSavedThisSession &&
				order.p2g?.canSyncLabelHash === true,
		}
	);
	const {
		labelSize,
		setLabelSize,
		downloadLabel,
		loading,
		error,
		labelSizeOptions,
	} = useLabelDownload(order.id);

	const handleShipMore = () => {
		window.location.assign(getLandingPageUrl());
	};

	return (
		<Card>
			<CardBody>
				{/* Top: P2G logo only when order has p2g meta */}
				{p2gLogo && (
					<Flex
						justify="center"
						align="center"
						style={{ marginBottom: 24 }}
					>
						<FlexItem>
							<img
								src={p2gLogo}
								alt="Parcel2Go"
								style={{
									height: 36,
									width: 'auto',
									display: 'block',
								}}
							/>
						</FlexItem>
					</Flex>
				)}

				{/* Centered content */}
				<Flex
					direction="column"
					align="center"
					gap={0}
					style={{
						textAlign: 'center',
						padding: '24px 16px',
						maxWidth: 560,
						margin: '0 auto',
					}}
				>
					<h1
						style={{
							margin: '0 0 8px',
							fontSize: '1.75rem',
							fontWeight: 700,
							color: '#1d2327',
						}}
					>
						{__('Order Complete', 'parcel2go-shipping')}
					</h1>
					<p
						style={{
							margin: '0 0 24px',
							fontSize: '1rem',
							color: '#50575e',
							lineHeight: 1.5,
						}}
					>
						{__(
							'Your shipping order has been processed successfully.',
							'parcel2go-shipping'
						)}
					</p>

					{hasParcel2GoBooking && (
						<>
							{transactionId && (
								<p
									style={{
										margin: '0 0 4px',
										fontSize: '1rem',
										fontWeight: 600,
										color: '#1d2327',
									}}
								>
									{__('TransactionID', 'parcel2go-shipping')}{' '}
									{transactionId}
								</p>
							)}
							{displayOrderLineIds.length > 0 && (
								<p
									style={{
										margin: '0 0 4px',
										fontSize: '1rem',
										fontWeight: 600,
										color: '#1d2327',
									}}
								>
									{__('P2G Order no', 'parcel2go-shipping')}{' '}
									{displayOrderLineIds.join(', ')}
								</p>
							)}
							<p
								style={{
									margin: '0 0 24px',
									fontSize: '0.875rem',
									color: '#757575',
								}}
							>
								{isFulfilled
									? __(
											'Ready for shipment',
											'parcel2go-shipping'
										)
									: __(
											'Booking in progress',
											'parcel2go-shipping'
										)}
							</p>
						</>
					)}

					{/* Success message box */}
					<Flex
						align="center"
						gap={3}
						style={{
							width: '100%',
							backgroundColor: '#edfaef',
							border: '1px solid #00a32a',
							borderRadius: 4,
							padding: '16px 20px',
							marginBottom: 24,
							textAlign: 'left',
						}}
					>
						<FlexItem
							style={{
								flexShrink: 0,
								color: '#00a32a',
								fontSize: 24,
							}}
						>
							&#10003;
						</FlexItem>
						<FlexItem style={{ flex: 1, minWidth: 0 }}>
							<p
								style={{
									margin: 0,
									fontSize: 14,
									color: '#1e4620',
									lineHeight: 1.5,
								}}
							>
								{__(
									'Order processed successfully.',
									'parcel2go-shipping'
								)}{' '}
								{__(
									"Your order has been booked and is ready to be shipped. We've automatically marked the order as complete in your WooCommerce store.",
									'parcel2go-shipping'
								)}
							</p>
						</FlexItem>
					</Flex>

					{isResolvingLabel && !showLabelDownload && (
						<Flex
							justify="center"
							align="center"
							gap={2}
							style={{ width: '100%', marginBottom: 8 }}
						>
							<Spinner />
							<span style={{ fontSize: 13, color: '#50575e' }}>
								{__('Loading label…', 'parcel2go-shipping')}
							</span>
						</Flex>
					)}

					{showLabelDownload && (
						<Flex
							direction="column"
							gap={3}
							style={{ width: '100%', alignItems: 'center' }}
						>
							<Flex
								direction="column"
								gap={1}
								style={{ width: '100%', alignItems: 'center' }}
							>
								<span
									style={{
										fontSize: 13,
										fontWeight: 600,
										color: '#1d2327',
									}}
								>
									{__('Label size', 'parcel2go-shipping')}
								</span>
								<ButtonGroup>
									{labelSizeOptions.map((option) => (
										<Button
											key={option.value}
											variant={
												labelSize === option.value
													? 'primary'
													: 'secondary'
											}
											size="small"
											onClick={() =>
												setLabelSize(option.value)
											}
											aria-pressed={
												labelSize === option.value
											}
											aria-label={option.label}
										>
											{option.shortLabel}
										</Button>
									))}
								</ButtonGroup>
							</Flex>
							<Button
								variant="primary"
								onClick={downloadLabel}
								disabled={loading}
								icon={loading ? <Spinner /> : download}
								iconPosition="left"
							>
								{loading
									? __('Loading…', 'parcel2go-shipping')
									: __(
											'Download label',
											'parcel2go-shipping'
										)}
							</Button>
							{error && (
								<p
									style={{
										margin: 0,
										fontSize: 12,
										color: 'var(--wp-admin-theme-color-darker, #1d2327)',
									}}
								>
									{error}
								</p>
							)}
						</Flex>
					)}

					{isFulfilled && (
						<Flex
							gap={2}
							justify="center"
							wrap
							style={{
								width: '100%',
								marginTop: showLabelDownload ? 8 : 0,
							}}
						>
							<Button
								variant="secondary"
								onClick={handleShipMore}
							>
								{__('Ship more orders', 'parcel2go-shipping')}
							</Button>
							<Button
								variant="secondary"
								href={P2G_HELP_URL}
								target="_blank"
								rel="noopener noreferrer"
								icon={help}
								iconPosition="left"
							>
								{__(
									'Get help with your order',
									'parcel2go-shipping'
								)}
							</Button>
						</Flex>
					)}

					{!isFulfilled && (
						<Flex gap={2} justify="center" wrap>
							<Button variant="secondary" onClick={onBack}>
								{__('Back to orders', 'parcel2go-shipping')}
							</Button>
							<Button
								variant="secondary"
								href={P2G_HELP_URL}
								target="_blank"
								rel="noopener noreferrer"
								icon={help}
								iconPosition="left"
							>
								{__(
									'Get help with your order',
									'parcel2go-shipping'
								)}
							</Button>
						</Flex>
					)}
				</Flex>
			</CardBody>
		</Card>
	);
}
