import { BaseControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
 * Read-only display of a submitted form payload. The value is either a JSON
 * string or an already-decoded object/array of key => value pairs. Used to show
 * the raw entry behind a lead/registration submission in the admin record view.
 */
const humanize = ( key ) =>
	String( key )
		.replace( /[_-]+/g, ' ' )
		.replace( /\b\w/g, ( c ) => c.toUpperCase() );

const SubmissionField = ( { field, value } ) => {
	let data = value;

	if ( typeof data === 'string' && data.trim() !== '' ) {
		try {
			data = JSON.parse( data );
		} catch ( e ) {
			data = { value: data };
		}
	}

	const entries =
		data && typeof data === 'object' && ! Array.isArray( data )
			? Object.entries( data )
			: [];

	return (
		<BaseControl
			label={ field.label }
			help={ field.help }
			__nextHasNoMarginBottom
		>
			{ entries.length === 0 ? (
				<p className="cliqthemes-ui-submission__empty">
					{ __( 'No submission data captured.', 'cliq-store-locator' ) }
				</p>
			) : (
				<table className="cliqthemes-ui-submission">
					<tbody>
						{ entries.map( ( [ key, val ] ) => (
							<tr key={ key }>
								<th scope="row">{ humanize( key ) }</th>
								<td>
									{ val === null || val === ''
										? '—'
										: typeof val === 'object'
											? JSON.stringify( val )
											: String( val ) }
								</td>
							</tr>
						) ) }
					</tbody>
				</table>
			) }
		</BaseControl>
	);
};

export default SubmissionField;
