import { memo } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { Tooltip } from '@wordpress/components';

import Badge from './badge';

export interface RenderWeightProps {
	formatted: string | null;
	hasNoWeight?: boolean;
	hasPartialMissingWeight?: boolean;
	missingWeightItems?: string[];
	missingWeightCount?: number;
}

function truncateLabel(value: string, maxLen: number = 40): string {
	if (value.length <= maxLen) return value;
	return `${value.slice(0, maxLen - 1)}...`;
}

function buildMissingWeightTooltipText(itemNames: string[]): string {
	const unique = Array.from(
		new Set(itemNames.map((name) => name.trim()).filter(Boolean))
	);
	if (!unique.length) {
		return __(
			'One or more items have no weight set. Go to product settings to add weight.',
			'parcel2go-shipping'
		);
	}

	const preview = unique.slice(0, 3).map((name) => truncateLabel(name, 40));
	const remaining = unique.length - preview.length;
	const baseList = preview.join(', ');

	if (remaining > 0) {
		return sprintf(
			__('No weight set for: %1$s (+%2$d more).', 'parcel2go-shipping'),
			baseList,
			remaining
		);
	}

	return sprintf(__('No weight set for: %s.', 'parcel2go-shipping'), baseList);
}

function RenderWeight({
	formatted,
	hasNoWeight = false,
	hasPartialMissingWeight = false,
	missingWeightItems = [],
	missingWeightCount = 0,
}: RenderWeightProps): React.ReactNode {
	if (hasNoWeight) {
		return (
			<Tooltip text={buildMissingWeightTooltipText(missingWeightItems)}>
				<span style={{ display: 'inline-flex', cursor: 'help' }}>
					<Badge tone="warning">{__('No weight', 'parcel2go-shipping')}</Badge>
				</span>
			</Tooltip>
		);
	}

	if (hasPartialMissingWeight) {
		return (
			<Tooltip text={buildMissingWeightTooltipText(missingWeightItems)}>
				<span style={{ display: 'inline-flex', cursor: 'help' }}>
					<Badge tone="warning">
						{sprintf(
							__(' (%s) weight issue', 'parcel2go-shipping'),
							missingWeightCount
						)}
					</Badge>
				</span>
			</Tooltip>
		);
	}

	return <span>{formatted ?? '—'}</span>;
}

export default memo(RenderWeight);
