import { field, type AdminRecord } from '../admin-data';

/**
 * Picks the most human-friendly display name for a launch/target record without
 * each section reaching into raw backend keys.
 * @param row
 * @param fallback
 */
export const recordTitle = (
	row: AdminRecord,
	fallback = 'Untitled'
): string =>
	field(
		row,
		'title',
		field( row, 'name', field( row, 'label', fallback ) )
	);

export const recordSubtitle = ( row: AdminRecord ): string =>
	field( row, 'subtitle', field( row, 'reference', field( row, 'id' ) ) );

export const recordGoLive = ( row: AdminRecord ): string =>
	formatFriendlyDateTime(
		field(
			row,
			'goLiveLabel',
			field( row, 'scheduledFor', field( row, 'goLive', '' ) )
		)
	);

const FIELD_LABELS: Record< string, string > = {
	'wordpress.title': 'Title',
	'wordpress.slug': 'Slug',
	'wordpress.content': 'Content',
	'wordpress.excerpt': 'Excerpt',
	'wordpress.status': 'Status',
	'wordpress.publish_date': 'Publish date',
	'wordpress.author': 'Author',
	'wordpress.featured_image': 'Featured image',
	'wordpress.menu_order': 'Menu order',
	'wordpress.parent': 'Parent page',
	'wordpress.page_template': 'Page template',
	'wordpress.categories': 'Categories',
	'wordpress.tags': 'Tags',
	'product.core.name': 'Product name',
	'product.core.type': 'Product type',
	'product.core.status': 'Status',
	'product.core.slug': 'Slug',
	'product.core.purchase_note': 'Purchase note',
	'product.core.menu_order': 'Menu order',
	'product.content.description': 'Description',
	'product.content.short_description': 'Short description',
	'product.pricing.regular_price': 'Regular price',
	'product.pricing.sale_price': 'Sale price',
	'product.pricing.sale_start': 'Sale starts',
	'product.pricing.sale_end': 'Sale ends',
	'product.inventory.sku': 'SKU',
	'product.inventory.global_unique_id': 'GTIN, UPC, EAN, or ISBN',
	'product.inventory.manage_stock': 'Manage stock',
	'product.inventory.stock_quantity': 'Stock quantity',
	'product.inventory.stock_status': 'Stock status',
	'product.inventory.backorders': 'Backorders',
	'product.inventory.low_stock_amount': 'Low stock threshold',
	'product.inventory.sold_individually': 'Sold individually',
	'product.shipping.weight': 'Weight',
	'product.shipping.dimensions.length': 'Length',
	'product.shipping.dimensions.width': 'Width',
	'product.shipping.dimensions.height': 'Height',
	'product.shipping.class_id': 'Shipping class',
	'product.tax.status': 'Tax status',
	'product.tax.class': 'Tax class',
	'product.media.featured_image_id': 'Featured image',
	'product.media.gallery_image_ids': 'Product gallery',
	'product.attributes.assignment': 'Attributes',
	'product.attributes.definitions': 'Attributes',
	'product.attributes.default_values': 'Default attributes',
	'product.downloads.downloadable': 'Downloadable product',
	'product.downloads.virtual': 'Virtual product',
	'product.downloads.files': 'Download files',
	'product.downloads.limit': 'Download limit',
	'product.downloads.expiry': 'Download expiry',
	'product.metadata.registered': 'Registered metadata',
	'product.metadata.raw': 'Raw metadata',
	'core.name': 'Product name',
	'core.type': 'Product type',
	'core.status': 'Status',
	'core.slug': 'Slug',
	'core.purchase_note': 'Purchase note',
	'core.menu_order': 'Menu order',
	'content.description': 'Description',
	'content.short_description': 'Short description',
	'pricing.regular_price': 'Regular price',
	'pricing.sale_price': 'Sale price',
	'pricing.sale_start': 'Sale starts',
	'pricing.sale_end': 'Sale ends',
	'inventory.sku': 'SKU',
	'inventory.global_unique_id': 'GTIN, UPC, EAN, or ISBN',
	'inventory.manage_stock': 'Manage stock',
	'inventory.stock_quantity': 'Stock quantity',
	'inventory.stock_status': 'Stock status',
	'inventory.backorders': 'Backorders',
	'inventory.low_stock_amount': 'Low stock threshold',
	'inventory.sold_individually': 'Sold individually',
	'shipping.weight': 'Weight',
	'shipping.dimensions.length': 'Length',
	'shipping.dimensions.width': 'Width',
	'shipping.dimensions.height': 'Height',
	'shipping.class_id': 'Shipping class',
	'tax.status': 'Tax status',
	'tax.class': 'Tax class',
	'media.featured_image_id': 'Featured image',
	'media.gallery_image_ids': 'Product gallery',
	'attributes.assignment': 'Attributes',
	'attributes.definitions': 'Attributes',
	'attributes.default_values': 'Default attributes',
	'downloads.downloadable': 'Downloadable product',
	'downloads.virtual': 'Virtual product',
	'downloads.files': 'Download files',
	'downloads.limit': 'Download limit',
	'downloads.expiry': 'Download expiry',
	'security.api_token': 'API token',
};

const humanizeFieldPart = ( part: string ): string => {
	const acronyms: Record< string, string > = {
		api: 'API',
		ean: 'EAN',
		gtin: 'GTIN',
		id: 'ID',
		isbn: 'ISBN',
		sku: 'SKU',
		upc: 'UPC',
		url: 'URL',
	};
	const normalized = part.toLowerCase();

	return (
		acronyms[ normalized ] ||
		normalized.charAt( 0 ).toUpperCase() + normalized.slice( 1 )
	);
};

export const formatFriendlyFieldLabel = (
	value: unknown,
	fallback = 'Field'
): string => {
	const text = String( value ?? '' ).trim();
	if ( ! text ) {
		return fallback;
	}
	if ( ! /[._-]/.test( text ) && /\s/.test( text ) ) {
		return text;
	}

	const normalized = text
		.replace( /^variation\.\{stable-key\}\./, '' )
		.replace( /\.+/g, '.' )
		.replace( /_+/g, '_' )
		.toLowerCase();

	if ( FIELD_LABELS[ normalized ] ) {
		return FIELD_LABELS[ normalized ];
	}

	const withoutNamespace = normalized.replace(
		/^(product|variation|wordpress|post|page|core|content|pricing|inventory|shipping|tax|media|attributes|downloads|security|metadata)\./,
		''
	);
	const parts = withoutNamespace
		.split( /[._-]+/ )
		.filter( ( part ) => part && 'raw' !== part && 'registered' !== part );

	if ( ! parts.length ) {
		return fallback;
	}

	return parts.map( humanizeFieldPart ).join( ' ' );
};

const parseDateTime = ( value: string ): Date | null => {
	const iso = value.match(
		/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?/
	);
	if ( iso ) {
		const [ , year, month, day, hour = '0', minute = '0', second = '0' ] =
			iso;
		return new Date(
			Number( year ),
			Number( month ) - 1,
			Number( day ),
			Number( hour ),
			Number( minute ),
			Number( second )
		);
	}

	const normalized = value
		.replace( /\s+[·–—]\s+/g, ' ' )
		.replace( /\s+-\s+/g, ' ' )
		.replace( /\s+/g, ' ' )
		.trim();
	const parsed = new Date( normalized );

	return Number.isNaN( parsed.getTime() ) ? null : parsed;
};

export const formatFriendlyDateTime = (
	value: unknown,
	fallback = '—'
): string => {
	const text = String( value ?? '' ).trim();
	if ( ! text || '—' === text || '-' === text ) {
		return fallback;
	}

	if (
		/^(today|tomorrow|now|before schedule|after run|pick|selected day|any time|site timezone)/i.test(
			text
		)
	) {
		return text;
	}

	const date = parseDateTime( text );
	if ( ! date ) {
		return text;
	}

	const hasTime = /(?:\d{1,2}:\d{2}|am|pm)/i.test( text );
	const dateLabel = date.toLocaleDateString( 'en-US', {
		month: 'long',
		day: 'numeric',
		year: 'numeric',
	} );

	if ( ! hasTime ) {
		return dateLabel;
	}

	const timeLabel = date.toLocaleTimeString( 'en-US', {
		hour: 'numeric',
		minute: '2-digit',
	} );

	return `${ dateLabel } at ${ timeLabel }`;
};
