/**
 * WordPress dependencies
 */
import { useSelect } from '@safe-wordpress/data';

/**
 * External dependencies
 */
import clsx from 'clsx';
import { EMPTY_ARRAY } from '@nelio-content/constants';
import { store as NC_DATA } from '@nelio-content/data';

/**
 * Internal dependencies
 */
import './style.scss';
import { store as NC_EDIT_POST } from '../../../store';
import { useMemo } from '@safe-wordpress/element';

export const Progress = (): JSX.Element | null => {
	const { completed, total } = useProgress();

	if ( ! total ) {
		return null;
	}

	return (
		<div className="nelio-content-tasks-progress">
			<div className="nelio-content-tasks-progress__bar-background">
				<div
					className={ clsx( {
						'nelio-content-tasks-progress__bar': true,
						'nelio-content-tasks-progress__bar--is-completed':
							completed === total,
					} ) }
					style={ {
						width: `${ Math.round(
							( completed * 100 ) / total
						) }%`,
					} }
				></div>
			</div>
			<div className="nelio-content-tasks-progress__percentage">
				{ Math.round( ( completed * 100 ) / total ) }%
			</div>
		</div>
	);
};

// =====
// HOOKS
// =====

const useProgress = () => {
	const tasks = useSelect( ( select ) => {
		const postId = select( NC_EDIT_POST ).getPostId();
		return select( NC_DATA ).getTasksRelatedToPost( postId ) ?? EMPTY_ARRAY;
	}, [] );

	return useMemo( () => {
		let completed = 0;

		for ( const t of tasks ) {
			if ( t.completed ) {
				completed++;
			}
		}

		return {
			completed,
			total: tasks.length,
		};
	}, [ tasks ] );
};
