/**
 * 汎用データテーブルコンポーネント
 *
 * ページネーション付きのテーブル表示。
 */
import { __ } from '@wordpress/i18n';
import { Button } from '@wordpress/components';

export default function DataTable( {
	columns,
	rows,
	total = 0,
	page = 1,
	perPage = 20,
	onPageChange,
	onRowClick,
	loading = false,
} ) {
	const safeRows = Array.isArray( rows ) ? rows : [];
	const totalPages = Math.max( 1, Math.ceil( total / perPage ) );

	return (
		<div className="conf-manager-table">
			{ loading && (
				<div className="conf-manager-table__loading">
					{ __( 'Loading...', 'conferencemanager' ) }
				</div>
			) }
			<table className="widefat striped">
				<thead>
					<tr>
						{ columns.map( ( col ) => (
							<th key={ col.key }>{ col.label }</th>
						) ) }
					</tr>
				</thead>
				<tbody>
					{ safeRows.length === 0 && ! loading ? (
						<tr>
							<td colSpan={ columns.length }>
								{ __( 'No data available.', 'conferencemanager' ) }
							</td>
						</tr>
					) : (
						safeRows.map( ( row, idx ) => (
							<tr
								key={ row.id || idx }
								onClick={ () => onRowClick && onRowClick( row ) }
								style={ onRowClick ? { cursor: 'pointer' } : {} }
							>
								{ columns.map( ( col ) => (
									<td key={ col.key }>
										{ col.render
											? col.render( row[ col.key ], row )
											: row[ col.key ] ?? '' }
									</td>
								) ) }
							</tr>
						) )
					) }
				</tbody>
			</table>

			{ total > perPage && (
				<div className="conf-manager-table__pagination">
					<Button
						variant="secondary"
						disabled={ page <= 1 }
						onClick={ () => onPageChange( page - 1 ) }
					>
						{ __( 'Previous', 'conferencemanager' ) }
					</Button>
					<span className="conf-manager-table__page-info">
						{ page } / { totalPages }
						{ ' ' }({ total }{ __( 'items', 'conferencemanager' ) })
					</span>
					<Button
						variant="secondary"
						disabled={ page >= totalPages }
						onClick={ () => onPageChange( page + 1 ) }
					>
						{ __( 'Next', 'conferencemanager' ) }
					</Button>
				</div>
			) }
		</div>
	);
}
