import { __ } from '@wordpress/i18n';
import { useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';
import { ajaxurl, certificates, quizpress_nonce } from '@QPUtils/helper';
import ProgressModal from '@QPComponents/ProgressModal';
import { Button } from '@chakra-ui/react';
import { primaryBtn } from '../../../../../assets/scss/chakra/recipe';

import './styles.scss';

const CertificateFontsDownload = () => {
	const addonsSavedData = useSelector( ( state ) => state.addons );
	const isActiveCertificates = addonsSavedData?.certificates;
	const dispatch = useDispatch();
	const hasDownloadedFonts = certificates?.fonts_downloaded;
	const [ showProgressModal, setShowProgressModal ] = useState( false );
	const eventSourceRef = useRef( null );
	const [ downloadProgress, setDownloadProgress ] = useState( {
		message: null,
		percentage: 0,
		isComplete: false,
	} );

	const startFontsDownload = () => {
		setShowProgressModal( true );

		const url = `${ ajaxurl }?action=quizpress_certificates/download_fonts&security=${ quizpress_nonce }`;
		eventSourceRef.current = new EventSource( url, {
			withCredentials: true,
		} );

		eventSourceRef.current.onmessage = ( event ) => {
			const message = JSON.parse( event.data );
			setDownloadProgress( ( prev ) => {
				if ( prev.isComplete ) {
					setShowProgressModal( false );
					return prev;
				}
				if ( message.type === 'percentage' ) {
					return {
						...prev,
						message: `${ message.message }% completed`,
						percentage: parseInt( message.message ),
					};
				}
				if ( message.type === 'message' ) {
					return {
						...prev,
						message: message.message,
					};
				}
				if ( message.type === 'complete' ) {
					eventSourceRef.current?.close();
					dispatch(
						showNotification( {
							message: message?.message,
							isShow: true,
							type: 'success',
						} )
					);
					return {
						message: message.message,
						percentage: 100,
						isComplete: true,
					};
				}
				return prev;
			} );
		};
		eventSourceRef.current.onerror = ( error ) => {
			eventSourceRef.current?.close();
			setShowProgressModal( false );

			dispatch(
				showNotification( {
					message: __( 'Download failed!', 'quizpress' ),
					isShow: true,
					type: 'error',
				} )
			);

			setDownloadProgress( ( prev ) => ( {
				...prev,
				message: 'An error occurred during font download.',
			} ) );
		};
	};

	return (
		isActiveCertificates &&
		! hasDownloadedFonts && (
			<div className="quizpress-fonts-download-content-content">
				<div className="quizpress-fonts-download-content-content__warning">
					<span className="quizpress-icon quizpress-icon--info"></span>
					<div>
						<h2 className="quizpress-fonts-download-content-content__warning-title">
							{ __(
								'Action Required: Download Fonts',
								'quizpress'
							) }
						</h2>
						<span className="quizpress-fonts-download-content-content__warning-subtitle">
							{ __(
								'You need to download the required font to generate certificates. Without this font, the certificates PDF cannot be created. Please download it now to continue.',
								'quizpress'
							) }
						</span>
					</div>
				</div>
				<div>
					<Button onClick={ startFontsDownload } { ...primaryBtn }>
						{ __( 'Download fonts', 'quizpress' ) }
					</Button>
				</div>
				<ProgressModal
					show={ showProgressModal }
					progress={ downloadProgress?.percentage ?? 0 }
					isComplete={ downloadProgress?.isComplete ?? false }
					title={ __( 'Download in Progress!', 'quizpress' ) }
					progressMessage={ downloadProgress?.message }
					successTitle={ __(
						'Fonts Download completed successfully!',
						'quizpress'
					) }
					successMessage={ __(
						'Your Fonts Download is successfully done—and you’re good to go now, take a moment to test it now!',
						'quizpress'
					) }
					close={ () => {
						if ( eventSourceRef.current ) {
							eventSourceRef.current.close();
						}
						setShowProgressModal( false );
						window.location.reload();
					} }
				/>
			</div>
		)
	);
};

export default CertificateFontsDownload;
