/* External dependencies */
import { __ } from "@wordpress/i18n";
import PropTypes from "prop-types";

/* Internal dependencies */
import buildDurationString from "./utils/8.2";

/**
 * This migration is necessary because the HTML markup changed, because in 8.3 the way
 * the "Time needed" text is rendered was changed.
 *
 * See https://github.com/Yoast/wordpress-seo/pull/10910.
 */

/**
 * Returns the component of the given How-to step to be rendered in a WordPress post
 * (e.g. not in the editor).
 *
 * @param {object} step The how-to step.
 *
 * @returns {Component} The component to be rendered.
 */
const LegacyHowToStep = ( step ) => {
	return (
		<li className={ "schema-how-to-step" } key={ step.id }>
			<strong
				className="schema-how-to-step-name"
				key={ step.id + "-name" }
			>
				{ step.name }
			</strong>
			{ " " }
			<p
				className="schema-how-to-step-text"
				key={ step.id + "-text" }
			>
				{ step.text }
			</p>
			{ " " }
		</li>
	);
};

/**
 * Returns the component to be used to render
 * the How-to block on Wordpress (e.g. not in the editor).
 *
 * @param {object} props the attributes of the How-to block.
 *
 * @returns {Component} The component representing a How-to block.
 */
export default function LegacyHowTo( props ) {
	let { steps } = props.attributes;
	const {
		hasDuration,
		days,
		hours,
		minutes,
		description,
		unorderedList,
		additionalListCssClasses,
		className,
	} = props.attributes;

	steps = steps
		? steps.map( ( step ) => {
			return (
				<LegacyHowToStep
					{ ...step }
					key={ step.id }
				/>
			);
		} )
		: null;

	const classNames       = [ "schema-how-to", className ].filter( ( item ) => item ).join( " " );
	const listClassNames   = [ "schema-how-to-steps", additionalListCssClasses ].filter( ( item ) => item ).join( " " );

	const timeString = buildDurationString( { days, hours, minutes } );

	return (
		<div className={ classNames }>
			{ ( hasDuration && typeof timeString === "string" && timeString.length > 0 ) &&
				<p className="schema-how-to-total-time">
					{ __( "Time needed:", "wordpress-seo" ) }
					&nbsp;
					{ timeString + ". " }
				</p>
			}
			<p className="schema-how-to-description">
				{ description }
			</p>
			{ " " }
			{ unorderedList
				? <ul className={ listClassNames }>{ steps }</ul>
				: <ol className={ listClassNames }>{ steps }</ol>
			}
		</div>
	);
}

LegacyHowTo.propTypes = {
	attributes: PropTypes.object,
};
