export type AdminRecord = Record< string, unknown >;

export interface NavigationItem {
	id: string;
	label: string;
	href: string;
	current?: string;
	parent?: string;
}

export interface AdminData extends AdminRecord {
	applicationName?: string;
	brandLogoFallbackUrl?: string;
	brandLogoUrl?: string;
	currentScreen?: string;
	navigation?: NavigationItem[];
	entitlementProfile?: string;
	entitlements?: AdminRecord;
	permissions?: AdminRecord;
}

const screenTitles: Record< string, string > = {
	'schedule-center': 'Dashboard',
	'all-changes': 'Scheduled changes',
	calendar: 'Calendar',
	targets: 'Addons',
	recordings: 'Record a Change',
	'runs-logs': 'History',
	notifications: 'Notifications',
	settings: 'Settings',
	'system-status': 'Help & System Check',
	modules: 'Addons',
	'design-system': 'Design System',
};

const screenSummaries: Record< string, string > = {
	'schedule-center':
		'See what is scheduled, what needs review, and whether the scheduler is ready.',
	'all-changes':
		'Review every scheduled change you can access, with safety state and permitted actions.',
	calendar:
		'Browse upcoming changes by date and confirm the site timezone before anything goes live.',
	targets: 'See which addons and site areas are ready for safe scheduling.',
	recordings:
		'Start a safe editing copy, review active recordings, and schedule recorded changes.',
	'runs-logs':
		'Review completed, failed, cancelled, restored, and run activity.',
	notifications:
		'Review notification delivery results and practical delivery settings.',
	settings:
		'Manage practical dashboard preferences, review policy, restore policy, and advanced tools.',
	'system-status':
		'Check scheduler health, compatibility, undo readiness, and support tools.',
	modules:
		'Review installed modules, extensions, dependency health, and compatibility status.',
	'design-system':
		"Review the copied JJ's Post and Product Scheduler design-system reference inside WordPress admin.",
};

const statusLabels: Record< string, string > = {
	ready: 'Ready',
	scheduled: 'Scheduled',
	running: 'Applying',
	restoring: 'Restoring',
	rolling_back: 'Restoring',
	successful: 'Completed',
	success: 'Completed',
	complete: 'Completed',
	completed: 'Completed',
	successful_with_warnings: 'Completed with warnings',
	warning: 'Needs review',
	provider_missing: 'Needs review',
	validation_blocker: 'Needs review',
	target_fingerprint_mismatch: 'Needs review',
	latest_value_changed: 'Needs review',
	queue_overdue: 'Needs review',
	scheduler_overdue: 'Needs review',
	failed: 'Failed',
	partially_failed: 'Partially completed',
	partial_failed: 'Partially completed',
	blocked: 'Needs review',
	needs_validation: 'Needs review',
	not_validated: 'Needs review',
	needs_approval: 'Needs review',
	cancelled: 'Cancelled',
	canceled: 'Cancelled',
	superseded: 'Cancelled',
	rolled_back: 'Restored',
	restored: 'Restored',
	rollback_failed: 'Restore failed',
	active: 'Active',
	recording: 'Recording',
	finalized: 'Completed',
	finalization_failed: 'Cleanup failed',
	expired: 'Old safe copy',
	pending: 'Needs cleanup',
	cleaned: 'Cleaned',
	retained: 'Needs review',
	stale: 'Needs review',
	draft: 'Draft',
	sent: 'Sent',
	skipped: 'Skipped',
	retry_scheduled: 'Retry scheduled',
	module_supported: 'Available',
	module_lifecycle_partial: 'Limited support',
	module_lifecycle_missing: 'Not supported yet',
	requires_extension: 'Requires extension',
	module_lifecycle_unknown: 'Planned',
	module_incompatible: 'Needs review',
	read_only_discovery: 'Diagnostics only',
	unsupported: 'Not supported yet',
	never_schedule: 'Diagnostics only',
	future_module_planned: 'Planned',
	unknown: 'Needs review',
};

const statusDescriptions: Record< string, string > = {
	draft: 'Created but not scheduled.',
	ready: 'Safe to schedule or ready for the planned time.',
	needs_validation: 'Review the safety check before this can go live safely.',
	not_validated: 'Review the safety check before this can go live safely.',
	needs_approval: 'Review the approval state before this can continue.',
	warning: 'Something needs review before this can go live safely.',
	blocked: 'Something needs review before this can go live safely.',
	provider_missing: 'A required feature is unavailable.',
	validation_blocker: 'A safety check is blocking this change.',
	target_fingerprint_mismatch: 'The item changed after this was scheduled.',
	latest_value_changed: 'The item changed after this was scheduled.',
	queue_overdue: 'The scheduler is overdue.',
	scheduler_overdue: 'The scheduler is overdue.',
	scheduled: 'Has a future go-live time.',
	running: 'Currently being applied.',
	successful: 'Applied successfully.',
	success: 'Applied successfully.',
	complete: 'Applied successfully.',
	completed: 'Applied successfully.',
	successful_with_warnings:
		'Applied successfully, but something should be reviewed.',
	partially_failed: 'Some changes worked and some did not.',
	partial_failed: 'Some changes worked and some did not.',
	failed: 'Could not be applied.',
	cancelled: 'Will not go live.',
	canceled: 'Will not go live.',
	superseded: 'Will not go live.',
	restoring: 'Undoing the change now.',
	rolling_back: 'Undoing the change now.',
	rolled_back: 'Previous values were restored.',
	restored: 'Previous values were restored.',
	rollback_failed: 'Previous values could not be restored.',
	finalized: 'Safe copy became a scheduled change.',
	finalization_failed:
		'Cleanup needs review before this safe copy can be removed.',
	expired: 'This safe copy is old enough to clean up.',
	pending: 'Cleanup has not started yet.',
	cleaned: 'Temporary safe copy data was removed.',
	retained: 'Temporary safe copy data was kept for review.',
	stale: 'Needs review before this can go live safely.',
	module_supported: 'This area is available for scheduling.',
	module_lifecycle_partial:
		'Some items or fields in this area can be scheduled.',
	module_lifecycle_missing: 'This area is not supported on this site yet.',
	requires_extension:
		'A dedicated extension is required for safe scheduling.',
	read_only_discovery:
		'This area can be inspected for diagnostics, but not scheduled.',
	unsupported: 'This area is not supported on this site yet.',
	unknown: 'Needs review before this can go live safely.',
};

export const safeArray = < T >( value: unknown ): T[] =>
	Array.isArray( value ) ? ( value as T[] ) : [];

export const safeRecord = ( value: unknown ): AdminRecord =>
	null !== value && 'object' === typeof value && ! Array.isArray( value )
		? ( value as AdminRecord )
		: {};

export const textValue = ( value: unknown, fallback = '' ): string => {
	if ( 'string' === typeof value ) {
		return value;
	}

	if ( 'number' === typeof value || 'boolean' === typeof value ) {
		return String( value );
	}

	return fallback;
};

export const field = ( row: AdminRecord, key: string, fallback = '' ): string =>
	textValue( row[ key ], fallback );

export const firstOf = (
	row: AdminRecord,
	keys: string[],
	fallback = ''
): string => {
	for ( const key of keys ) {
		const value = field( row, key );
		if ( value ) {
			return value;
		}
	}

	return fallback;
};

export const numberValue = ( value: unknown ): number =>
	'number' === typeof value
		? value
		: Number.parseInt( textValue( value, '0' ), 10 ) || 0;

export const screenTitle = ( screen: string, fallback = '' ): string =>
	screenTitles[ screen ] || fallback || "JJ's Post and Product Scheduler";

export const screenSummary = ( screen: string ): string =>
	screenSummaries[ screen ] ||
	'Manage scheduled changes with safe defaults and permission-aware actions.';

const statusKey = ( value: unknown ): string =>
	textValue( value, 'unknown' )
		.trim()
		.toLowerCase()
		.replace( /[\s-]+/g, '_' );

export const statusLabel = ( value: unknown ): string => {
	const key = statusKey( value );

	return statusLabels[ key ] || 'Needs review';
};

export const statusDescription = ( value: unknown ): string => {
	const key = statusKey( value );

	return (
		statusDescriptions[ key ] ||
		statusDescriptions.unknown ||
		'Needs review before this can go live safely.'
	);
};

export const statusTone = ( value: unknown ): string => {
	const key = statusKey( value );

	if (
		[
			'ready',
			'scheduled',
			'successful',
			'success',
			'complete',
			'completed',
			'cleaned',
			'finalized',
			'rolled_back',
			'restored',
			'sent',
			'module_supported',
		].includes( key )
	) {
		return 'ready';
	}

	if (
		[
			'failed',
			'partially_failed',
			'partial_failed',
			'rollback_failed',
			'finalization_failed',
			'module_incompatible',
		].includes( key )
	) {
		return 'danger';
	}

	if (
		[
			'running',
			'needs_approval',
			'needs_validation',
			'not_validated',
			'warning',
			'blocked',
			'provider_missing',
			'validation_blocker',
			'target_fingerprint_mismatch',
			'latest_value_changed',
			'queue_overdue',
			'scheduler_overdue',
			'expired',
			'pending',
			'retained',
			'stale',
			'retry_scheduled',
			'module_lifecycle_partial',
			'module_lifecycle_missing',
			'requires_extension',
			'module_lifecycle_unknown',
		].includes( key )
	) {
		return 'warning';
	}

	return 'warning';
};

export const launchHealth = ( launch: AdminRecord ): string =>
	textValue( launch.health, textValue( launch.status, 'unknown' ) );

export const launchNeedsReview = ( launch: AdminRecord ): boolean =>
	[
		'failed',
		'partially_failed',
		'partial_failed',
		'blocked',
		'needs_validation',
		'not_validated',
		'needs_approval',
		'warning',
		'rollback_failed',
		'provider_missing',
		'validation_blocker',
		'target_fingerprint_mismatch',
		'latest_value_changed',
		'queue_overdue',
		'scheduler_overdue',
		'stale',
		'unknown',
	].includes( statusKey( launchHealth( launch ) ) );

export const navigationForScreen = (
	items: NavigationItem[] | undefined,
	screen: string
): NavigationItem | undefined =>
	safeArray< NavigationItem >( items ).find( ( item ) => item.id === screen );

export const screenFromNavigationHref = (
	items: NavigationItem[] | undefined,
	href: string,
	baseHref = 'http://scheduled-changes.local/'
): string => {
	let target: URL;

	try {
		target = new URL( href, baseHref );
	} catch {
		return '';
	}

	for ( const item of safeArray< NavigationItem >( items ) ) {
		try {
			const itemUrl = new URL( item.href, baseHref );
			const targetPage = target.searchParams.get( 'page' );
			const itemPage = itemUrl.searchParams.get( 'page' );

			if ( targetPage && itemPage && targetPage === itemPage ) {
				return item.id;
			}

			if (
				target.pathname === itemUrl.pathname &&
				target.search === itemUrl.search
			) {
				return item.id;
			}
		} catch {
			continue;
		}
	}

	return '';
};

export const permission = ( data: AdminData, key: string ): boolean =>
	true === safeRecord( data.permissions )[ key ];

export const entitlement = ( data: AdminData, key: string ): boolean =>
	'' === key || true === safeRecord( data.entitlements )[ key ];

export const featureAvailable = (
	data: AdminData,
	entitlementKey: string,
	permissionKey = ''
): boolean =>
	entitlement( data, entitlementKey ) &&
	( '' === permissionKey || permission( data, permissionKey ) );

export const featureLockReason = (
	data: AdminData,
	entitlementKey: string,
	permissionKey = '',
	label = 'This feature'
): string => {
	if ( ! entitlement( data, entitlementKey ) ) {
		return `${ label } is not available in this product profile.`;
	}

	if ( permissionKey && ! permission( data, permissionKey ) ) {
		return `${ label } is unavailable for this account.`;
	}

	return '';
};
