/**
 * WordPress dependencies
 */
import { useSelect } from '@safe-wordpress/data';
import { useState } from '@safe-wordpress/element';
import { _x, sprintf } from '@safe-wordpress/i18n';
import { addQueryArgs } from '@safe-wordpress/url';
import apiFetch from '@safe-wordpress/api-fetch';
import { gmdate } from '@safe-wordpress/date';

/**
 * External dependencies
 */
import { ConfirmationDialog } from '@nelio-content/components';

/**
 * Internal dependencies
 */
import { store as NC_ANALYTICS } from '~/nelio-content-pages/analytics/store';

export type ExportDialogProps = {
	readonly onClose: () => void;
};

export const ExportDialog = ( { onClose }: ExportDialogProps ): JSX.Element => {
	const criteria = useSelect(
		( select ) => select( NC_ANALYTICS ).getFilterCriteria(),
		[]
	);

	const [ isExporting, setIsExporting ] = useState< boolean >( false );

	const exportCsv = () => {
		const { periodMode, periodValue: period } = criteria;
		if ( 'custom' === periodMode ) {
			if ( ! period.from || ! period.to ) {
				return;
			}
		}
		const { sortBy: sortByCriterion, author, postType: type } = criteria;

		const path = addQueryArgs(
			'/nelio-content/v1/analytics/top-posts/export',
			{
				sortBy: sortByCriterion,
				from: period.from || undefined,
				to: period.to || undefined,
				author: author ? author : undefined,
				postType: '_nc-all' !== type ? type : undefined,
			}
		);

		setIsExporting( true );

		apiFetch( {
			path,
			method: 'GET',
			parse: false,
		} )
			.then( ( response: Response | string ) => {
				// With parse:false, apiFetch resolves to the native Response object.
				if ( response instanceof window.Response ) {
					return response.text();
				}
				// Just in case, if something returns a string already:
				return response;
			} )
			.then( ( csv: string ) => {
				const url = window.URL || window.webkitURL;
				const blob = new window.Blob( [ csv ], {
					type: 'text/csv;charset=UTF-8',
				} );

				const element = document.createElement( 'a' );
				element.setAttribute( 'href', url.createObjectURL( blob ) );
				element.setAttribute(
					'download',
					sprintf(
						'nelio-content-analytics-%s.csv',
						gmdate( 'Ymd-His' )
					)
				);

				document.body.appendChild( element );
				element.click();
				document.body.removeChild( element );
			} )
			.catch( ( error ) => {
				// eslint-disable-next-line no-console
				console.error( 'Error exporting analytics CSV', error );
			} )
			.finally( () => {
				setIsExporting( false );
				onClose();
			} );
	};

	return (
		<ConfirmationDialog
			title={ _x( 'Export Analytics?', 'text', 'nelio-content' ) }
			text={ _x(
				'This will export a CSV with the analytics of all posts matching the current filters.',
				'text',
				'nelio-content'
			) }
			confirmLabel={
				isExporting
					? _x( 'Exporting…', 'command', 'nelio-content' )
					: _x( 'Export CSV', 'command', 'nelio-content' )
			}
			isConfirmBusy={ isExporting }
			isOpen={ true }
			isCancelEnabled={ ! isExporting }
			isConfirmEnabled={ ! isExporting }
			onCancel={ onClose }
			onConfirm={ exportCsv }
		/>
	);
};
