/**
 * Inspector: switch among Original + Owner variants with live thumbs.
 * Used as a top-level Variant tab (peer of Page / Block), not a Block accordion.
 */
import {
	createElement,
	Fragment,
	useCallback,
	useMemo,
	useState,
} from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import { createBlock } from '@wordpress/blocks';
import ConfirmModal from '../components/ConfirmModal';
import VariantLayerThumb from '../admin/components/VariantLayerThumb';
import { brandLogoUrl } from '../shared/brandLogo';
import { findVariantFamily, skipPickerOnce } from './libraryVariants';

export function hasLibraryVariants( meta ) {
	const family = findVariantFamily( meta?.name );
	return Boolean( family?.choices?.length && family.choices.length >= 2 );
}

function choiceTitle( choice, index ) {
	return (
		choice?.title ||
		choice?.systemName ||
		( index === 0
			? __( 'Original', 'joc-blockora-morph' )
			: __( 'Variant', 'joc-blockora-morph' ) )
	);
}

export default function LibraryVariantSwitcher( { meta, clientId } ) {
	const { replaceBlocks } = useDispatch( 'core/block-editor' );
	const [ pending, setPending ] = useState( null );
	const family = useMemo(
		() => findVariantFamily( meta?.name ),
		[ meta?.name ]
	);

	const cancelPending = useCallback( () => {
		setPending( null );
	}, [] );

	const confirmPending = useCallback( () => {
		if ( ! pending?.name || ! clientId ) {
			setPending( null );
			return;
		}
		skipPickerOnce.add( pending.name );
		replaceBlocks( clientId, createBlock( pending.name ) );
		setPending( null );
	}, [ pending, clientId, replaceBlocks ] );

	if ( ! family?.choices?.length || family.choices.length < 2 ) {
		return null;
	}

	const pendingTitle = pending
		? choiceTitle(
				pending,
				family.choices.findIndex( ( c ) => c.name === pending.name )
		  )
		: '';

	return createElement(
		Fragment,
		null,
		createElement(
			'div',
			{ className: 'jocbm-library-variant-switcher' },
			createElement(
				'header',
				{ className: 'jocbm-library-variant-switcher__head' },
				createElement(
					'div',
					{ className: 'jocbm-library-variant-switcher__brand' },
					createElement(
						'span',
						{
							className:
								'jocbm-library-variant-switcher__logo',
							'aria-hidden': true,
						},
						createElement( 'img', {
							src: brandLogoUrl(),
							alt: '',
							width: 36,
							height: 36,
							decoding: 'async',
						} )
					),
					createElement(
						'div',
						{
							className:
								'jocbm-library-variant-switcher__head-copy',
						},
						createElement(
							'span',
							{
								className:
									'jocbm-library-variant-switcher__eyebrow',
							},
							__( 'JBM Template Library', 'joc-blockora-morph' )
						),
						createElement(
							'h2',
							{
								className:
									'jocbm-library-variant-switcher__heading',
							},
							__( 'Choose a variant', 'joc-blockora-morph' )
						)
					),
					createElement(
						'span',
						{
							className:
								'jocbm-library-variant-switcher__count',
						},
						sprintf(
							/* translators: %d: number of available variants */
							__( '%d available', 'joc-blockora-morph' ),
							family.choices.length
						)
					)
				),
				createElement(
					'p',
					{ className: 'jocbm-library-variant-switcher__intro' },
					__(
						'Switch the look of this library block. Content edits on the current look are not carried over.',
						'joc-blockora-morph'
					)
				)
			),
			createElement(
				'div',
				{
					className: 'jocbm-library-variant-switcher__grid',
					role: 'listbox',
					'aria-label': __(
						'Template variants',
						'joc-blockora-morph'
					),
				},
				family.choices.map( ( choice, index ) => {
					const selected = choice.name === meta.name;
					const title = choiceTitle( choice, index );
					const onActivate = () => {
						if ( selected || ! clientId || ! choice.name ) {
							return;
						}
						// Keep visual selection on the current variant until
						// the user confirms — only open the confirm modal.
						setPending( choice );
					};
					return createElement(
						'div',
						{
							key: choice.name,
							role: 'option',
							tabIndex: 0,
							'aria-selected': selected,
							className:
								'jocbm-library-variant-switcher__card' +
								( selected ? ' is-selected' : '' ) +
								( pending?.name === choice.name
									? ' is-pending'
									: '' ),
							title,
							onClick: onActivate,
							onKeyDown: ( e ) => {
								if ( e.key === 'Enter' || e.key === ' ' ) {
									e.preventDefault();
									onActivate();
								}
							},
						},
						createElement(
							'span',
							{
								className:
									'jocbm-library-variant-switcher__thumb',
							},
							createElement( VariantLayerThumb, {
								block: choice,
								label: title,
							} )
						),
						createElement(
							'span',
							{
								className:
									'jocbm-library-variant-switcher__badge',
							},
							index === 0
								? __( 'Original', 'joc-blockora-morph' )
								: __( 'Variant', 'joc-blockora-morph' )
						),
						createElement(
							'strong',
							{
								className:
									'jocbm-library-variant-switcher__title',
							},
							title
						)
					);
				} )
			)
		),
		createElement( ConfirmModal, {
			open: Boolean( pending ),
			title: __( 'Change template variant?', 'joc-blockora-morph' ),
			description: sprintf(
				/* translators: %s: target variant title */
				__(
					'Switching to “%s” replaces this block’s content and styles. Edits on the current look will not carry over.',
					'joc-blockora-morph'
				),
				pendingTitle
			),
			icon: 'image-rotate',
			tone: 'warning',
			confirmLabel: __( 'Change variant', 'joc-blockora-morph' ),
			cancelLabel: __( 'Keep current', 'joc-blockora-morph' ),
			onCancel: cancelPending,
			onConfirm: confirmPending,
		} )
	);
}
