import type { PrepareImportFileResponse } from '../../typings/types';
import { __ } from '@wordpress/i18n';

function doesImportFileContainCondtionTypeCol(
	fileContents: Array<Array<string>>
) {
	for (let i = 0; i < fileContents.length; i++) {
		if (['any', 'all'].includes(fileContents[i][0])) {
			return true;
		}
	}

	return false;
}

export function getRowConditionLabel(
	row: PrepareImportFileResponse['data']['disambiguation']['rows'][number],
	fileContents: Array<Array<string>>
) {
	const productColIdx = doesImportFileContainCondtionTypeCol(fileContents)
		? 1
		: 0;

	let rowLabel = __('Row', 'gp-conditional-pricing');

	for (let i = row.index + 1; i < fileContents.length; i++) {
		if (fileContents[i][productColIdx]) {
			rowLabel = fileContents[i][productColIdx];
			break;
		}
	}

	let rowValuePreview = Object.values(row.values).join(', ');
	const totalMaxLen = 35;
	const previewMaxLen = totalMaxLen - rowLabel.length;

	if (previewMaxLen > 0 && rowValuePreview.length > previewMaxLen) {
		rowValuePreview = `${rowValuePreview
			.slice(0, previewMaxLen)
			// remove any commas at the end of the string as they look funky.
			.replace(/,$/, '')}...`;
	}

	rowLabel = `${rowLabel} (${rowValuePreview})`;

	return rowLabel;
}
