import { useBlockProps, useInnerBlocksProps, InspectorControls } from '@wordpress/block-editor';
import { useState } from '@wordpress/element';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
import { useDeviceSettings, generateBlockStyles } from '../../components/controls/blockStyles';
import { generateBlockStylesHover } from '../../components/controls/blockStylesHover';
import { TABLE_CELL_BLOCK } from '../table/utils';
import { ElementStylePanel } from '../table/components/ElementStylePanel';

export default function Edit( { attributes, setAttributes, clientId } ) {
	const { anchor, uniqueClass } = attributes;

	useUniqueBlockClass( { clientId, uniqueClass, setAttributes, blockName: 'axcelersblocks-table-row' } );

	const devices = useDeviceSettings();
	const [ activeStyleTab, setActiveStyleTab ] = useState( 'main' );

	const blockProps = useBlockProps( {
		id: anchor || undefined,
		className: [ 'axcelersblocks-table-row', uniqueClass ].filter( Boolean ).join( ' ' ),
	} );

	// Cells are the source of truth; rows/columns are edited from the cell toolbar
	// (no numeric sync), so the row just renders its cells.
	const innerBlocksProps = useInnerBlocksProps( blockProps, {
		allowedBlocks: [ TABLE_CELL_BLOCK ],
		templateLock: false,
		renderAppender: false,
		orientation: 'horizontal',
	} );

	return (
		<>
			<InspectorControls>
				<ElementStylePanel
					attributes={ attributes }
					setAttributes={ setAttributes }
					uniqueClass={ uniqueClass }
					selectorLabel={ uniqueClass ? `.${ uniqueClass }` : 'tr' }
					activeTab={ activeStyleTab }
					setActiveTab={ setActiveStyleTab }
				/>
			</InspectorControls>

			{ uniqueClass ? (
				<style>
					{ generateBlockStyles( uniqueClass, devices, attributes ) }
					{ generateBlockStylesHover( uniqueClass, devices, attributes ) }
				</style>
			) : null }

			<tr { ...innerBlocksProps } />
		</>
	);
}
