import { __, sprintf } from '@wordpress/i18n';
import { Placeholder } from '@wordpress/components';
import { useState } from '@wordpress/element';
import { grid as gridIcon } from '@wordpress/icons';

const MAX_ROWS = 12;
const MAX_COLS = 12;

// Creation-only grid picker for the Table block. Hovering a cell (r, c)
// highlights an r×c block and previews the size; clicking creates the table.
// After the table exists this placeholder is never shown again.
export default function TablePlaceholder( { onCreate } ) {
	// 1-based hovered position; 0 means "nothing hovered".
	const [ hover, setHover ] = useState( { rows: 0, cols: 0 } );

	const label =
		hover.rows && hover.cols
			? sprintf(
					/* translators: 1: number of rows, 2: number of columns. */
					__( '%1$d × %2$d', 'axcelersblocks' ),
					hover.rows,
					hover.cols
			  )
			: __( 'Select size', 'axcelersblocks' );

	return (
		<Placeholder
			icon={ gridIcon }
			label={ __( 'Create Table', 'axcelersblocks' ) }
			instructions={ __(
				'Pick the number of rows and columns. You can add or remove them later.',
				'axcelersblocks'
			) }
		>
			<div className="axcelersblocks-table-grid-picker">
				<div
					className="axcelersblocks-table-grid-picker__grid"
					aria-label={ __( 'Table size', 'axcelersblocks' ) }
					onMouseLeave={ () => setHover( { rows: 0, cols: 0 } ) }
				>
					{ Array.from( { length: MAX_ROWS }, ( _, r ) => (
						<div
							className="axcelersblocks-table-grid-picker__row"
							key={ r }
						>
							{ Array.from(
								{ length: MAX_COLS },
								( __cell, c ) => {
									const rows = r + 1;
									const cols = c + 1;
									const isActive =
										rows <= hover.rows &&
										cols <= hover.cols;
									return (
										<button
											key={ c }
											type="button"
											className={ [
												'axcelersblocks-table-grid-picker__cell',
												isActive ? 'is-active' : '',
											]
												.filter( Boolean )
												.join( ' ' ) }
											aria-label={ sprintf(
												/* translators: 1: rows, 2: columns. */
												__(
													'Create a %1$d by %2$d table',
													'axcelersblocks'
												),
												rows,
												cols
											) }
											onMouseEnter={ () =>
												setHover( { rows, cols } )
											}
											onFocus={ () =>
												setHover( { rows, cols } )
											}
											onClick={ () =>
												onCreate( {
													rows,
													columns: cols,
												} )
											}
										/>
									);
								}
							) }
						</div>
					) ) }
				</div>
				<div className="axcelersblocks-table-grid-picker__label">
					{ label }
				</div>
			</div>
		</Placeholder>
	);
}
