import React, { useContext } from 'react';
import { __ } from '@wordpress/i18n';
import { FormikWizard } from 'formik-wizard-form';
import { QuizContext, QuizStatusContext } from '../QuizContext';
import { getFormikQuizSteps } from './helper';
import { useDispatch, useSelector } from 'react-redux';
import {
	insertAttemptQuestion,
	updateAttempts,
} from '@QPRedux/Slices/quizInsightsSlice/quizInsightsSlice';
import { user_id } from '@QPUtils/helper';
import QuizTimeExpire from './QuizTimeExpire';
import QuizHeader from './QuizHeader';
import { Box, Text } from '@chakra-ui/react';

const Quiz = ( {
	ID,
	setSteps,
	attemptId,
	totalAttempts,
	handleFetchAttempts,
	handleStartQuiz,
	currentQuiz,
} ) => {
	const { setLoading } = useContext( QuizStatusContext );
	const quizzes = useSelector( ( state ) => state.quizzes );
	const { attempt_questions } = useSelector(
		( state ) => state.quizInsights
	);
	const dispatch = useDispatch();

	const onSubmitFormHandler = ( values, { setSubmitting, resetForm } ) => {
		setLoading( true );
		const payload = {
			...values,
			total_questions: attempt_questions.length,
			total_answered_questions: Object.values( values.answers ).filter(
				( ans ) => ans !== null && ans !== undefined && ans !== ''
			).length,
			attempt_id: attemptId,
			attempt_status: 'pending',
			quiz_id: ID,
			user_id,
		};

		setTimeout( () => {
			dispatch( updateAttempts( payload ) ).then( () => {
				handleFetchAttempts();
				dispatch( insertAttemptQuestion( [] ) );
				setSteps( 0 );
				setTimeout( () => {
					setLoading( false );
				}, 500 );
			} );
		}, 500 );

		setSubmitting( false );
	};

	const stepsArr = getFormikQuizSteps(
		attempt_questions,
		currentQuiz.meta?.quizpress_quiz_questions_order,
		totalAttempts,
		currentQuiz
	);

	return (
		<>
			{ ! attempt_questions?.length ? (
				<Text>
					{ __(
						'No questions found. Please add questions and try again',
						'quizpress'
					) }
				</Text>
			) : (
				<FormikWizard
					enableReinitialize={ true }
					initialValues={ {
						quiz_id: ID,
						attempt:
							totalAttempts.find(
								( item ) =>
									Number( item.attempt_id ) ===
									Number( attemptId )
							) || {},
						answers: {},
						attempt_id: attemptId,
						is_time_expire: false,
					} }
					onSubmit={ onSubmitFormHandler }
					validateOnNext
					activeStepIndex={ 0 }
					steps={ stepsArr }
				>
					{ ( {
						currentStepIndex,
						renderComponent,
						handlePrev,
						handleNext,
						isNextDisabled,
						isPrevDisabled,
						isLastStep,
						values,
					} ) => {
						const hasRequiredId = ID && attemptId;
						const currentQuestion =
							stepsArr[ currentStepIndex ]?.question;
						return (
							<QuizContext.Provider
								value={ {
									currentStepIndex,
									renderComponent,
									handlePrev,
									handleNext,
									isNextDisabled,
									isPrevDisabled,
									isLastStep,
									attempts: totalAttempts,
								} }
							>
								<>
									{ values.is_time_expire ? (
										<QuizTimeExpire
											handleStartQuiz={ handleStartQuiz }
											totalAttempts={ totalAttempts }
											currentQuiz={ currentQuiz }
										/>
									) : (
										<Box
											borderRadius="8px"
											width="100%"
											maxW={ {
												base: '100%',
												md: '720px',
											} }
											bg="var(--quizpress-background)"
											background="#F6F7F8"
											shadow="var(--quizpress-shadow)"
											p={ 6 }
										>
											<Box
												width="100%"
												p={ 6 }
												borderRadius="8px"
												bg="var(--quizpress-background)"
											>
												<QuizHeader
													currentQuiz={
														quizzes.data[ 0 ]
													}
													attempts={ totalAttempts }
													stepIndex={
														currentStepIndex
													}
													currentQuestion={
														currentQuestion
													}
												/>
												{ hasRequiredId &&
													renderComponent() }
											</Box>
										</Box>
									) }
								</>
							</QuizContext.Provider>
						);
					} }
				</FormikWizard>
			) }
		</>
	);
};

export default Quiz;
