import { useMemo, useState } from '@wordpress/element';
import { runLegacyAjax } from '../api';

const COLUMNS = [
	{ id: 'overdue', dot: 'red' },
	{ id: 'due-soon', dot: 'amber' },
	{ id: 'scheduled', dot: 'blue' },
	{ id: 'done', dot: 'gray' },
];

export function KanbanBoard( { tasks, i18n, onMoved } ) {
	const [ dragging, setDragging ] = useState( null );
	const [ busy, setBusy ] = useState( false );

	const buckets = useMemo( () => {
		const out = { overdue: [], 'due-soon': [], scheduled: [], done: [] };
		( tasks || [] ).forEach( ( t ) => {
			const col = t.kanbanColumn || t.statusKey || 'scheduled';
			if ( out[ col ] ) {
				out[ col ].push( t );
			}
		} );
		return out;
	}, [ tasks ] );

	const labels = {
		overdue: i18n.col_overdue || 'Overdue',
		'due-soon': i18n.col_due_soon || 'Due soon',
		scheduled: i18n.col_scheduled || 'Scheduled',
		done: i18n.col_done || 'Done',
	};

	const moveTask = async ( taskId, column ) => {
		setBusy( true );
		try {
			await runLegacyAjax( 'newsai_kanban_move_task', { task_id: taskId, column } );
			onMoved?.( taskId, column );
		} catch ( e ) {
			window.alert( e?.message || 'Move failed' );
		} finally {
			setBusy( false );
			setDragging( null );
		}
	};

	return (
		<div className={ `nros-kanban${ busy ? ' is-busy' : '' }` }>
			{ COLUMNS.map( ( col ) => (
				<div
					key={ col.id }
					className="nros-kanban__col"
					onDragOver={ ( e ) => e.preventDefault() }
					onDrop={ ( e ) => {
						e.preventDefault();
						if ( dragging ) {
							moveTask( dragging, col.id );
						}
					} }
				>
					<div className="nros-kanban__col-head">
						<span className={ `nros-kanban__dot nros-kanban__dot--${ col.dot }` } />
						<span>{ labels[ col.id ] }</span>
						<span className="nros-kanban__count">{ ( buckets[ col.id ] || [] ).length }</span>
					</div>
					<div className="nros-kanban__cards">
						{ ( buckets[ col.id ] || [] ).map( ( t ) => (
							<div
								key={ t.id }
								className="nros-kanban__card"
								draggable
								onDragStart={ () => setDragging( t.id ) }
								onDragEnd={ () => setDragging( null ) }
							>
								<div className="nros-kanban__card-title">{ t.title }</div>
								<div className="nros-kanban__card-meta">
									{ t.keyword && <span className="nros-kanban__tag">{ t.keyword }</span> }
									<span className="nros-kanban__avatar" title={ t.assignee }>{ t.initials || '—' }</span>
								</div>
							</div>
						) ) }
					</div>
				</div>
			) ) }
		</div>
	);
}
