import { __, sprintf } from '@wordpress/i18n';
import type { FixAction, FixRequest } from '../../shared/api/types/fixes';
import type { LinkDetail } from '../../shared/api/types/links';
import { problemOf, type Problem } from '../../shared/links/problem';
import { boot } from '../../shared/lib/boot';
import { fieldUrl } from '../../shared/lib/url';
import type { IconName } from '../../shared/ui/Icon';

export type FixPlan = {
	problem: Problem;
	isRedirect: boolean;
	needsAddress: boolean;
	prefilledAddress: string;
};

export type PrimaryFix = {
	action: FixAction;
	label: string;
	icon: IconName | undefined;
};

export function fixPlanOf( link: LinkDetail ): FixPlan {
	const problem = problemOf( link );
	const isRedirect = problem === 'broken' && link.internal;
	const wantsPrefill = problem === 'moved' || isRedirect;
	const suggestedUrl = link.suggested_url ?? '';
	const prefilledAddress =
		wantsPrefill && suggestedUrl !== ''
			? fieldUrl( suggestedUrl, boot.siteUrl )
			: '';

	return {
		problem,
		isRedirect,
		needsAddress: problem !== 'blocked',
		prefilledAddress,
	};
}

export function primaryFixOf(
	plan: FixPlan,
	typedAddress: string,
	placesText: string
): PrimaryFix {
	if ( plan.isRedirect ) {
		return {
			action: 'redirect',
			label: __( 'Create redirect', 'aiplaz-link-checkup' ),
			icon: 'redirect',
		};
	}

	switch ( plan.problem ) {
		case 'broken':
			return {
				action: 'replace',
				label: sprintf(
					/* translators: %s: number of places, for example "3 places" */
					__( 'Replace in %s', 'aiplaz-link-checkup' ),
					placesText
				),
				icon: undefined,
			};
		case 'moved':
			return {
				action:
					typedAddress.trim() === plan.prefilledAddress
						? 'update'
						: 'replace',
				label: sprintf(
					/* translators: %s: number of places, for example "3 places" */
					__( 'Update in %s', 'aiplaz-link-checkup' ),
					placesText
				),
				icon: undefined,
			};
		case 'blocked':
			return {
				action: 'works',
				label: __( 'It works', 'aiplaz-link-checkup' ),
				icon: 'check',
			};
	}
}

function needsNewUrl( action: FixAction ): boolean {
	return action === 'replace' || action === 'redirect';
}

export function fixRequestOf(
	action: FixAction,
	linkId: number,
	typedAddress: string
): FixRequest {
	const request: FixRequest = { action, link_ids: [ linkId ] };

	if ( needsNewUrl( action ) ) {
		return { ...request, new_url: typedAddress.trim() };
	}

	return request;
}
