/**
 * External Dependencies
 */
import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as noticesStore } from '@wordpress/notices';
import { RefreshCw } from 'lucide-react';

/**
 * Internal Dependencies
 */
import { STORE_NAME } from '@admin/store';
import { clsx } from '@admin/utils';
import {
	extractApiErrorMessage,
	syncLicensesFromShop,
} from '../hooks/licenses-api';
import {
	LICENSE_NOTICES_CONTEXT,
	publishLicenseSuccessNotice,
	publishLicenseWarningNotice,
} from './LicenseNotices';

const SYNC_NOTICE_ID = 'advanced-ads/license-sync';

/**
 * Render the button for syncing licenses from the shop.
 *
 * @return {React.ReactNode} The sync button or null when no licenses exist.
 */
export function SyncLicensesButton() {
	const hasLicenses = useSelect(
		( select ) => select( STORE_NAME ).hasLicenses(),
		[]
	);
	const { createSuccessNotice, createErrorNotice, removeNotice } =
		useDispatch( noticesStore );
	const [ busy, setBusy ] = useState( false );

	if ( ! hasLicenses ) {
		return null;
	}

	/**
	 * Sync licenses with the shop and display the result as a notice.
	 *
	 * @return {Promise<void>} Resolves when the sync request is complete.
	 */
	async function handleSync() {
		if ( busy ) {
			return;
		}

		setBusy( true );

		try {
			await syncLicensesFromShop();

			removeNotice( SYNC_NOTICE_ID, LICENSE_NOTICES_CONTEXT );

			publishLicenseSuccessNotice( createSuccessNotice, {
				id: SYNC_NOTICE_ID,
				context: LICENSE_NOTICES_CONTEXT,
				title: __( 'Licenses synced', 'advanced-ads' ),
				message: __(
					'Your licenses are up to date with the shop.',
					'advanced-ads'
				),
				icon: 'success',
			} );
		} catch ( err ) {
			removeNotice( SYNC_NOTICE_ID, LICENSE_NOTICES_CONTEXT );

			publishLicenseWarningNotice( createErrorNotice, {
				id: SYNC_NOTICE_ID,
				context: LICENSE_NOTICES_CONTEXT,
				message:
					extractApiErrorMessage( err ) ||
					__( 'Could not sync licenses.', 'advanced-ads' ),
			} );
		} finally {
			setBusy( false );
		}
	}

	return (
		<button
			type="button"
			className={ clsx(
				'group ml-auto button bg-gray-200 hover:bg-gray-300 text-black hover:text-black text-xs px-3 py-1.5 min-h-0',
				busy ? 'bg-green-200! hover:bg-green-200!' : ''
			) }
			disabled={ busy }
			aria-label={
				busy
					? __( 'Syncing licenses', 'advanced-ads' )
					: __( 'Sync licenses', 'advanced-ads' )
			}
			onClick={ handleSync }
		>
			<RefreshCw
				className={ clsx(
					'size-3',
					busy ? 'animate-spin' : 'group-hover:stroke-current'
				) }
			/>
			{ busy
				? __( 'Syncing', 'advanced-ads' )
				: __( 'Sync', 'advanced-ads' ) }
		</button>
	);
}
