import React, { useEffect, useRef, useState } from 'react';
import { useFormikContext } from 'formik';
import { __ } from '@wordpress/i18n';
import { timeStringGenerator, timeToSecondsGenerator } from '@QPUtils/helper';
import { Flex, Span } from '@chakra-ui/react';

const QuizTimer = ( { isTimeExpire, time, unit } ) => {
	const { setFieldValue } = useFormikContext();

	const Ref = useRef( null );

	const [ timer, setTimer ] = useState( timeStringGenerator( time, unit ) );

	const getTimeRemaining = ( e ) => {
		const total = Date.parse( e ) - Date.parse( new Date() );
		const seconds = Math.floor( ( total / 1000 ) % 60 );
		const minutes = Math.floor( ( total / 1000 / 60 ) % 60 );
		const hours = Math.floor( ( total / 1000 / 60 / 60 ) % 24 );
		return {
			total,
			hours,
			minutes,
			seconds,
		};
	};

	const startTimer = ( e ) => {
		const { total, hours, minutes, seconds } = getTimeRemaining( e );

		if ( time === Number( 0 ) ) {
			return;
		}

		if ( total >= 0 && ! isTimeExpire ) {
			setTimer(
				( hours > 9 ? hours : '0' + hours ) +
					':' +
					( minutes > 9 ? minutes : '0' + minutes ) +
					':' +
					( seconds > 9 ? seconds : '0' + seconds )
			);
		} else {
			setFieldValue( 'is_time_expire', true );
			clearInterval( Ref.current );
		}
	};

	const clearTimer = ( e ) => {
		setTimer( timeStringGenerator( time, unit ) );

		if ( Ref.current ) {
			clearInterval( Ref.current );
		}
		const id = setInterval( () => {
			startTimer( e );
		}, 1000 );
		Ref.current = id;
	};

	const getDeadTime = () => {
		const deadline = new Date();

		deadline.setSeconds(
			deadline.getSeconds() + timeToSecondsGenerator( time, unit )
		);
		return deadline;
	};

	useEffect( () => {
		clearTimer( getDeadTime() );
	}, [ isTimeExpire ] );

	return (
		<Flex
			gap={ 2 }
			alignItems="center"
			fontSize="sm"
			m={ 0 }
			fontWeight="500"
		>
			<Span color="var(--quizpress-warn-muted)">
				{ __( 'Time remaining:', 'quizpress' ) }
			</Span>
			<Span>{ isTimeExpire ? __( 'Expired', 'quizpress' ) : timer }</Span>
		</Flex>
	);
};

export default QuizTimer;
