/**
 * WordPress dependencies
 */
import apiFetch from '@safe-wordpress/api-fetch';
import { Button } from '@safe-wordpress/components';
import { dispatch } from '@safe-wordpress/data';
import { useState } from '@safe-wordpress/element';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { store as NC_DATA } from '@nelio-content/data';
import type { Post, PostId } from '@nelio-content/types';

export type PostRefreshAnalyticsActionProps = {
	readonly postId: PostId;
};

export const PostRefreshAnalyticsAction = ( {
	postId,
}: PostRefreshAnalyticsActionProps ): JSX.Element => {
	const [ isProcessing, setIsProcessing ] = useState( false );

	const refreshAnalytics = () => {
		setIsProcessing( true );
		void apiFetch( {
			path: `/nelio-content/v1/analytics/post/${ postId }/update`,
			method: 'POST',
		} )
			.then( () => {
				void apiFetch< Post >( {
					path: `/nelio-content/v1/post/${ postId }`,
				} )
					.then( ( post ) => {
						void dispatch( NC_DATA )
							.receivePosts( post )
							.catch( () => {
								setIsProcessing( false );
							} )
							.finally( () => {
								setIsProcessing( false );
							} );
					} )
					.catch( () => {
						setIsProcessing( false );
					} );
			} )
			.catch( () => {
				setIsProcessing( false );
			} );
	};

	return (
		<Button
			className="nelio-content-refresh-analytics-action"
			variant="link"
			isBusy={ isProcessing }
			disabled={ isProcessing }
			onClick={ refreshAnalytics }
		>
			{ isProcessing
				? _x( 'Refreshing…', 'text', 'nelio-content' )
				: _x( 'Refresh Analytics', 'command', 'nelio-content' ) }
		</Button>
	);
};
