import { IconifyIcon, type ScheduledChangesIconName } from '../iconify';
import { StatusBadge } from '../primitives/StatusBadge';
import type { CompatibilityRow } from '../selectors';

const COMPAT_META: Record<
	CompatibilityRow[ 'status' ],
	{ led: string; tone: 'success' | 'running' | 'canceled'; label: string }
> = {
	ok: { led: 'led-ok', tone: 'success', label: 'Fully supported' },
	warn: { led: 'led-warn', tone: 'running', label: 'Addon needed' },
	soon: { led: 'led-warn', tone: 'running', label: 'Coming soon' },
	off: { led: 'led-bad', tone: 'canceled', label: 'Not yet' },
};

const iconForCompatibilityRow = (
	row: CompatibilityRow
): ScheduledChangesIconName => {
	const name = row.name.toLowerCase();

	if ( name.includes( 'variation' ) ) {
		return 'variations';
	}
	if ( name.includes( 'product' ) || name.includes( 'woocommerce' ) ) {
		return 'products';
	}
	if ( name.includes( 'page' ) ) {
		return 'pages';
	}
	if ( name.includes( 'post' ) ) {
		return 'posts';
	}
	if ( name.includes( 'raw metadata' ) ) {
		return 'metadata-raw';
	}
	if ( name.includes( 'metadata' ) ) {
		return 'metadata-safe';
	}
	if ( name.includes( 'advanced custom fields' ) ) {
		return 'custom-fields';
	}
	if ( name.includes( 'plugin' ) ) {
		return 'custom-plugin';
	}

	return 'addon';
};

export const CompatibilityMatrix = ( {
	rows,
	variant = 'rows',
}: {
	rows: CompatibilityRow[];
	variant?: 'grid' | 'rows';
} ) => (
	<div
		className={ 'grid' === variant ? 'compat-grid' : undefined }
		data-stagger
	>
		{ rows.map( ( row ) => {
			const meta = COMPAT_META[ row.status ];
			const icon = iconForCompatibilityRow( row );

			if ( 'grid' === variant ) {
				return (
					<div className="card compat-card" key={ row.name }>
						<span className="compat-card-icon" aria-hidden="true">
							<IconifyIcon name={ icon } />
						</span>
						<div className="cr-main">
							<div>
								<div className="nm">{ row.name }</div>
								<div className="sub">{ row.detail }</div>
							</div>
							<StatusBadge tone={ meta.tone }>
								{ meta.label }
							</StatusBadge>
						</div>
					</div>
				);
			}

			return (
				<div className="compat-row" key={ row.name }>
					<span
						className={ `stat-led ${ meta.led }` }
						style={
							'off' === row.status
								? {
										background: 'var(--status-canceled)',
										boxShadow:
											'0 0 0 3px var(--status-canceled-soft)',
								  }
								: undefined
						}
					></span>
					<div className="cr-main">
						<div className="nm">{ row.name }</div>
						<div className="sub">{ row.detail }</div>
					</div>
					<StatusBadge tone={ meta.tone }>{ meta.label }</StatusBadge>
				</div>
			);
		} ) }
	</div>
);
