import { __ } from '@wordpress/i18n';
import {
	useBlockProps,
	useInnerBlocksProps,
	InspectorControls,
	store as blockEditorStore,
} from '@wordpress/block-editor';
import { useState } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import { TabPanel, Button } from '@wordpress/components';
import { cog, styles, plus } from '@wordpress/icons';
import './editor.scss';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
import {
	useDeviceSettings,
	generateBlockStyles,
} from '../../components/controls/blockStyles';
import { generateBlockStylesHover } from '../../components/controls/blockStylesHover';
import { TABLE_SECTION_BLOCK, createTableFromGrid } from './utils';
import { useAddSection } from './structureActions';
import { SettingsPanel } from './components/SettingsPanel';
import { StylePanel } from './components/StylePanel';
import TablePlaceholder from './components/TablePlaceholder';

const getTableSummary = ( sections ) => {
	const rows = sections.flatMap( ( section ) => section.innerBlocks || [] );
	const columnCount = rows.reduce( ( maxColumns, row ) => {
		const rowColumns = ( row.innerBlocks || [] ).reduce(
			( total, cell ) =>
				total + Math.max( 1, cell.attributes?.colSpan || 1 ),
			0
		);
		return Math.max( maxColumns, rowColumns );
	}, 0 );
	const cellCount = rows.reduce(
		( total, row ) => total + ( row.innerBlocks || [] ).length,
		0
	);

	return {
		columns: columnCount,
		rows: rows.length,
		cells: cellCount,
	};
};

// Build a single <colgroup> from the `cols` attribute. Only set values are
// emitted, so an unconfigured column stays a bare <col>.
const renderColgroup = ( cols ) => {
	if ( ! Array.isArray( cols ) || cols.length === 0 ) {
		return null;
	}
	return (
		<colgroup>
			{ cols.map( ( col, index ) => {
				const span = Math.max( 1, parseInt( col?.span, 10 ) || 1 );
				const style = {};
				if ( col?.width ) {
					style.width = col.width;
				}
				if ( col?.backgroundColor ) {
					style.backgroundColor = col.backgroundColor;
				}
				return (
					<col
						key={ index }
						span={ span > 1 ? span : undefined }
						style={
							Object.keys( style ).length ? style : undefined
						}
					/>
				);
			} ) }
		</colgroup>
	);
};

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

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

	const devices = useDeviceSettings();
	const [ activeStyleTab, setActiveStyleTab ] = useState( 'main' );
	const { children, isActive } = useSelect(
		( select ) => {
			const store = select( blockEditorStore );
			return {
				children: store.getBlocks( clientId ),
				isActive:
					store.isBlockSelected( clientId ) ||
					store.hasSelectedInnerBlock( clientId, true ),
			};
		},
		[ clientId ]
	);
	const { replaceInnerBlocks } = useDispatch( blockEditorStore );
	const addSection = useAddSection( clientId );

	// Editor-only wrapper so the "Add" controls can sit outside the <table>
	// flow (a button inside <tr>/<tbody> would become a stray cell).
	const blockProps = useBlockProps( {
		className: 'axcelersblocks-table__editor',
	} );

	const { children: innerChildren, ...innerBlocksProps } =
		useInnerBlocksProps(
			{
				id: anchor || undefined,
				className: [ 'axcelersblocks-table', uniqueClass ]
					.filter( Boolean )
					.join( ' ' ),
			},
			{
				allowedBlocks: [ TABLE_SECTION_BLOCK ],
				templateLock: false,
				renderAppender: false,
				orientation: 'vertical',
			}
		);
	const tableSummary = getTableSummary( children );

	// Creation-only: until the first section exists, show the grid picker
	// instead of an empty table.
	if ( children.length === 0 ) {
		return (
			<div { ...blockProps }>
				<TablePlaceholder
					onCreate={ ( { rows, columns } ) =>
						replaceInnerBlocks(
							clientId,
							createTableFromGrid( { rows, columns } ),
							false
						)
					}
				/>
			</div>
		);
	}

	return (
		<>
			<InspectorControls>
				<TabPanel
					className="axcelersblocks-tabs"
					activeClass="is-active"
					tabs={ [
						{
							name: 'settings',
							title: <>{ cog }</>,
							className: 'settings-tab',
						},
						{
							name: 'style',
							title: <>{ styles }</>,
							className: 'style-tab',
						},
					] }
				>
					{ ( tab ) => (
						<>
							{ tab.name === 'settings' && (
								<SettingsPanel
									attributes={ attributes }
									setAttributes={ setAttributes }
									summary={ tableSummary }
								/>
							) }
							{ tab.name === 'style' && (
								<StylePanel
									attributes={ attributes }
									setAttributes={ setAttributes }
									uniqueClass={ uniqueClass }
									activeTab={ activeStyleTab }
									setActiveTab={ setActiveStyleTab }
								/>
							) }
						</>
					) }
				</TabPanel>
			</InspectorControls>

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

			<div
				{ ...blockProps }
				className={ [
					blockProps.className,
					isActive ? 'is-table-active' : '',
				]
					.filter( Boolean )
					.join( ' ' ) }
			>
				<table { ...innerBlocksProps }>
					{ renderColgroup( cols ) }
					{ innerChildren }
				</table>

				{ /* Table-level inserter: a new section is appended below the table. */ }
				<div
					className="axb-table-inserter axb-table-inserter--section"
					contentEditable={ false }
				>
					<Button
						className="axb-table-inserter__btn"
						icon={ plus }
						onClick={ addSection }
					>
						{ __( 'Add Section', 'axcelersblocks' ) }
					</Button>
				</div>
			</div>
		</>
	);
}
