import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import { Flex, Input, Text } from '@chakra-ui/react';
import { getQuiz } from '@QPRedux/Slices/quizSlice/quizSlice';
import { API, makeRequest, namespace, user_id } from '@QPUtils/helper';
import {
	createAttempts,
	insertAttemptQuestion,
} from '@QPRedux/Slices/quizInsightsSlice/quizInsightsSlice';
import ReactModalFormik from '@QPComponents/Modal/ReactModalFormik';
import { Field } from 'formik';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';
import QuizView from './QuizView';
import Preloader from '@QPComponents/Loader/Preloader';
import { QuizStatusContext } from './QuizContext';
import { isAllowReAttempt } from './helper';
import './styles.scss';

const StartQuiz = ( { ID } ) => {
	const quizzes = useSelector( ( state ) => state.quizzes );
	const [ attemptsData, setAttemptsData ] = useState( {} );
	const [ loading, setLoading ] = useState( false );
	const [ starterLoading, setStarterLoading ] = useState( false );
	const [ isModalOpen, setIsModalOpen ] = useState( false );
	const [ steps, setSteps ] = useState( 0 );
	const [ attemptsCount, setAttemptsCount ] = useState( 0 );
	const [ currentAttempt, setCurrentAttempt ] = useState( null );
	const [ successMessage, setSuccessMessage ] = useState( null );
	const autoStartTriggeredRef = React.useRef( false );

	const dispatch = useDispatch();
	const currentQuiz = quizzes.data[ 0 ] ?? null;

	const handleFetchAttempts = () => {
		makeRequest( 'frontend/get_user_attempt_by_quiz', {
			quiz_id: ID,
		} ).then( ( res ) => {
			setAttemptsData( res );
		} );
	};

	const handleGetQuiz = async () => {
		if ( ! quizzes.data.length ) {
			setLoading( true );
			dispatch( getQuiz( { ID } ) )
				.then( () => {
					if ( Number( user_id ) ) {
						handleFetchAttempts();
					}
				} )
				.finally( () => {
					setTimeout( () => {
						setLoading( false );
					}, 500 );
				} );
		}
	};

	useEffect( () => {
		handleGetQuiz();
	}, [ ID ] );

	useEffect( () => {
		if ( ! currentQuiz ) {
			return;
		}
		if ( ! Object.keys( attemptsData )?.length ) {
			return;
		}

		if (
			! attemptsData?.status &&
			currentQuiz.meta?.quizpress_quiz_auto_start &&
			! autoStartTriggeredRef.current
		) {
			autoStartTriggeredRef.current = true;
			handleStartQuiz();
		}
	}, [ currentQuiz, attemptsData ] );

	const handleStartQuiz = async () => {
		if ( ! Number( user_id ) ) {
			setIsModalOpen( true );
			return;
		}

		const acceptReAttempt =
			( attemptsData &&
				currentQuiz?.meta?.quizpress_quiz_feedback_mode === 'default' &&
				attemptsData?.attempts?.length < 1 ) ||
			isAllowReAttempt(
				currentQuiz?.meta?.quizpress_quiz_feedback_mode,
				currentQuiz?.meta?.quizpress_quiz_max_attempts_allowed,
				attemptsData?.attempts?.length
			);

		if ( ! acceptReAttempt ) {
			dispatch(
				showNotification( {
					message: __(
						'You have reached the maximum number of attempts.',
						'quizpress'
					),
					type: 'error',
					isShow: true,
				} )
			);
			return;
		}

		setStarterLoading( true );
		try {
			makeRequest( 'frontend/get_quiz_questions_for_attempt', {
				quiz_id: ID,
			} ).then( async ( res ) => {
				dispatch( insertAttemptQuestion( res.questions ) );
				const attemptResponse = await dispatch(
					createAttempts( {
						quiz_id: ID,
						user_id,
						attempt_info: {
							total_correct_answers: 0,
							render_question_ids: res?.render_question_ids,
						},
					} )
				).unwrap();
				setCurrentAttempt( attemptResponse );
				setAttemptsCount( attemptsCount + 1 );
				setSteps( 1 );
				setTimeout( () => {
					setStarterLoading( false );
				}, 500 );
			} );
		} catch ( error ) {
			console.error( 'Failed to start quiz:', error );
		} finally {
			// setStarterLoading(false);
		}
	};

	return (
		<>
			{ loading || ! currentQuiz ? (
				<Preloader />
			) : (
				<Flex
					direction="column"
					gap={ 6 }
					width="100%"
					bg="transparent"
					borderRadius="4px"
					margin="auto"
				>
					<QuizStatusContext.Provider
						value={ {
							loading,
							setLoading,
							starterLoading,
							setStarterLoading,
							attemptsCount,
							setAttemptsCount,
						} }
					>
						<QuizView
							steps={ steps }
							ID={ ID }
							currentAttempt={ currentAttempt }
							attemptsData={ attemptsData }
							setSteps={ setSteps }
							handleFetchAttempts={ handleFetchAttempts }
							handleStartQuiz={ handleStartQuiz }
						/>
					</QuizStatusContext.Provider>

					<ReactModalFormik
						isOpen={ isModalOpen }
						onRequestClose={ () => {
							setIsModalOpen( false );
							setSuccessMessage( null );
						} }
						title={ __( 'Sign in to start the quiz', 'quizpress' ) }
						isLargeAvailable={ false }
						isEnabledResizer={ false }
						size="small"
						submitButtonLabel={ __(
							'Give me login url',
							'quizpress'
						) }
						isEnabledFooter={ successMessage ? false : true }
						cancelButtonLabel={ false }
						formik={ {
							enableReInitialize: true,
							initialValues: { email: '' },
							onSubmit: async ( values, actions ) => {
								const { email } = values;

								if ( ! email ) {
									dispatch(
										showNotification( {
											message: __(
												'Email is required',
												'quizpress'
											),
											isShow: true,
											type: 'error',
										} )
									);
									actions.setSubmitting( false );
									return;
								}

								try {
									const result = await API.post(
										`${ namespace }magic-login`,
										{ email }
									);
									if ( result.data.success ) {
										setSuccessMessage(
											__(
												result.data.message,
												'quizpress'
											)
										);
									} else {
										dispatch(
											showNotification( {
												message: __(
													'Something went wrong. Try again later.',
													'quizpress'
												),
												isShow: true,
												type: 'error',
											} )
										);
									}
								} catch {
									dispatch(
										showNotification( {
											message: __(
												'Network error. Please try again.',
												'quizpress'
											),
											isShow: true,
											type: 'error',
										} )
									);
								} finally {
									actions.setSubmitting( false );
								}
							},
						} }
						suffix="frontend-login-modal"
					>
						<Flex direction="column" gap={ 3 } p="0 22px">
							{ successMessage ? (
								<Text
									fontSize="0.95rem"
									fontWeight={ 500 }
									color="green.600"
									textAlign="center"
									mt={ 2 }
								>
									{ successMessage }
								</Text>
							) : (
								<>
									<Text
										m={ 0 }
										fontSize="0.875rem"
										fontWeight={ 600 }
									>
										{ __( 'Email', 'quizpress' ) }
									</Text>
									<Field
										name="email"
										as={ Input }
										type="email"
										placeholder={ __(
											'Enter your email',
											'quizpress'
										) }
									/>
								</>
							) }
						</Flex>
					</ReactModalFormik>
				</Flex>
			) }
		</>
	);
};

export default StartQuiz;
