import ErrorState from '@/components/ui/error-state';
import { describeErrorScreen } from '@/utils/errorScreen';

/**
 * Error screen for a failed API call. Picks the copy from the error type
 * (utils/errorScreen) so a lost WordPress session, a network hiccup or a
 * server error each read right, and wires the action: a session/login
 * problem reloads the page (WordPress then asks the user to log in and brings
 * them back here), anything else calls `onRetry`.
 *
 * @param {object}    props
 * @param {Error}     props.error
 * @param {string}    [props.fallbackTitle]        What we were doing, in Flavio's voice
 * @param {string}    [props.fallbackDescription]
 * @param {() => void} [props.onRetry]
 * @param {boolean}   [props.retrying]
 * @param {string}    [props.className]
 */
const ApiErrorState = ({
	error,
	fallbackTitle,
	fallbackDescription,
	onRetry,
	retrying = false,
	className,
}) => {
	const { title, description, actionLabel, technicalDetails, reload } =
		describeErrorScreen(error, { fallbackTitle, fallbackDescription });

	const onAction = reload ? () => window.location.reload() : onRetry;

	return (
		<ErrorState
			title={title}
			description={description}
			actionLabel={actionLabel}
			onAction={onAction}
			actionPending={retrying}
			technicalDetails={technicalDetails}
			className={className}
		/>
	);
};

export default ApiErrorState;
