import { useMemo } from '@wordpress/element';

export function TaskTable( { tasks, filter, i18n, caps, onEdit } ) {
	const filtered = useMemo( () => {
		return ( tasks || [] ).filter( ( t ) => {
			if ( filter === 'overdue' ) {
				return t.overdue && t.status !== 'done';
			}
			if ( filter === 'today' ) {
				return t.dueToday && t.status !== 'done';
			}
			if ( filter === 'unassigned' ) {
				return t.unassigned && t.status !== 'done';
			}
			if ( filter === 'done' ) {
				return t.status === 'done';
			}
			return true;
		} );
	}, [ tasks, filter ] );

	const onAction = ( url, kind ) => {
		if ( ! url ) {
			return;
		}
		const msg = kind === 'delete' ? i18n.confirm_delete : i18n.confirm_done;
		if ( kind === 'delete' || kind === 'done' ) {
			if ( ! window.confirm( msg ) ) {
				return;
			}
		}
		window.location.href = url;
	};

	return (
		<div className="newsroom-dash__table-wrap">
			<table className="newsroom-dash__table widefat striped">
				<thead>
					<tr>
						<th>{ i18n.col_task }</th>
						<th>{ i18n.col_date }</th>
						<th>{ i18n.col_writer }</th>
						<th>{ i18n.col_status }</th>
						<th>{ i18n.col_actions }</th>
					</tr>
				</thead>
				<tbody>
					{ filtered.length === 0 && (
						<tr><td colSpan={ 5 }>{ i18n.no_tasks }</td></tr>
					) }
					{ filtered.map( ( t ) => (
						<tr key={ t.id } data-status-key={ t.statusKey }>
							<td>
								<strong>{ t.title }</strong>
								{ t.keyword && <div className="newsroom-dash__task-kw">🔑 { t.keyword }</div> }
							</td>
							<td>{ t.dateLabel }</td>
							<td>{ t.assignee }</td>
							<td>
								<span className={ `newsroom-dash__status newsroom-dash__status--${ t.statusKey }` }>
									{ t.statusLabel }
								</span>
							</td>
							<td>
								<div className="newsroom-dash__actions">
									{ ( onEdit || t.actions?.edit ) && (
										<button type="button" className="button button-small" onClick={ () => ( onEdit ? onEdit( t ) : window.location.href = t.actions.edit ) }>
											{ i18n.actions_edit }
										</button>
									) }
									{ t.actions?.done && (
										<button type="button" className="button button-small" onClick={ () => onAction( t.actions.done, 'done' ) }>
											{ i18n.actions_done }
										</button>
									) }
									{ t.actions?.delete && caps?.manageAll && (
										<button type="button" className="button button-small" onClick={ () => onAction( t.actions.delete, 'delete' ) }>
											{ i18n.actions_delete }
										</button>
									) }
								</div>
							</td>
						</tr>
					) ) }
				</tbody>
			</table>
		</div>
	);
}
