import React, { useContext } from 'react';
import { Flex, Button, Text } from '@chakra-ui/react';
import { QuizContext } from '../QuizContext';
import { useFormikContext } from 'formik';
import { __, sprintf } from '@wordpress/i18n';
import { outlineBtn, primaryBtn } from '../../../../assets/scss/chakra/recipe';
import { makeRequest } from '@QPUtils/helper';
import SingleChoiceText from './quizTypes/SingleChoiceText';
import SingleChoiceRich from './quizTypes/SingleChoiceRich';
import ImageAnswer from './quizTypes/ImageAnswer';
import ImageTextAnswer from './quizTypes/ImageTextAnswer';
import OptIn from './quizTypes/OptIn';
import TrueFalse from './quizTypes/TrueFalse';
import { buildSubmitableAnswers } from './helper';
import ReadOnlyBlanks from './quizTypes/ReadOnlyBlanks';
import { useDispatch } from 'react-redux';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';

const QuizAnswer = ( { question, currentQuiz } ) => {
	if ( ! question ) {
		return;
	} //Todo: Need to update it later

	const { handleNext, handlePrev, isLastStep, currentStepIndex } =
		useContext( QuizContext );
	const { values, setFieldValue, handleSubmit } = useFormikContext();

	const dispatch = useDispatch();
	const isAnswerRequired =
		currentQuiz?.meta?.quizpress_quiz_force_all_questions_required ||
		question?.question_settings?.answer_required;
	const isAnswered = values?.answers?.[ question.question_id ]?.length;

	const handleAnswerSubmit = async ( payload = null ) => {
		try {
			await makeRequest( 'frontend/insert_quiz_answer', payload );
		} catch ( error ) {
			console.error( error );
		}
	};

	const submitAnswer = ( goNext = false ) => {
		const submitableAnswers = buildSubmitableAnswers( question, values );
		handleAnswerSubmit( {
			quiz_id: values?.quiz_id,
			question_id: question.question_id,
			given_answers: JSON.stringify( submitableAnswers ),
			attempt_id: values.attempt_id,
		} );

		if ( goNext ) {
			handleNext();
		}
	};

	const handleChange = ( e ) => {
		const val = e.value;
		const qType = question.question_type;
		const fieldPath = `answers.${ question.question_id }`;

		if (
			[
				'multiple_choice',
				'multiple_choice_horizontal',
				'fill_in_the_blanks',
			].includes( qType )
		) {
			setFieldValue( fieldPath, val );
		} else {
			setFieldValue( fieldPath, [ val ] );
		}
	};

	const answerType = question.answer_type;
	const answers = question?.answers;

	const ansComponentProps = {
		handleChange,
		answers,
		question,
	};

	const renderSwitchQuestionType = ( questionType ) => {
		switch ( questionType ) {
			case 'single_choice':
			case 'multiple_choice':
			case 'multiple_choice_horizontal':
			case 'single_choice_horizontal':
			case 'drop_down':
				if ( answerType === 'plain_text' ) {
					return (
						<SingleChoiceText
							{ ...ansComponentProps }
							questionType={ questionType }
						/>
					);
				}
				if ( answerType === 'rich_text' ) {
					return (
						<SingleChoiceRich
							{ ...ansComponentProps }
							questionType={ questionType }
						/>
					);
				}
				if ( answerType === 'image' ) {
					return (
						<ImageAnswer
							{ ...ansComponentProps }
							questionType={ questionType }
						/>
					);
				}
				if ( answerType === 'image_and_text' ) {
					return (
						<ImageTextAnswer
							{ ...ansComponentProps }
							questionType={ questionType }
						/>
					);
				}
				break;
			case 'opt_in':
			case 'date':
			case 'paragraph':
			case 'short_answer':
			case 'number':
			case 'file_upload':
			case 'captcha':
				return (
					<OptIn
						{ ...ansComponentProps }
						questionType={ questionType }
						handleAnswerSubmit={ handleAnswerSubmit }
					/>
				);
			case 'fill_in_the_blanks':
				if ( answerType === 'read_only' ) {
					return (
						<ReadOnlyBlanks
							{ ...ansComponentProps }
							questionType={ questionType }
						/>
					);
				}
				// if (answerType === 'sequent') {
				// 	return <SequentBlanks
				// 		ansName="answers"
				// 		ansVal={values?.answers ?? []}
				// 	/>;
				// }
				break;
			case 'true_false':
				return (
					<TrueFalse
						{ ...ansComponentProps }
						questionType={ questionType }
					/>
				);
			// case 'checkbox_grid':
			// case 'radio_grid':
			// return <GridRowColumn index={index} />

			case 'text_html': {
				//todo:need to update answer
				if ( ! values?.answers?.[ question.question_id ] ) {
					setFieldValue(
						`answers.${ question.question_id }`,
						question.question_content
					);
				}
				return (
					<Text>
						{ __( question.question_content, 'quizpress' ) }
					</Text>
				);
			}
		}
	};

	return (
		<Flex direction="column" gap={ 6 } width="100%" margin="auto">
			<Flex
				flexDirection="column"
				alignItems="center"
				width="100%"
				margin="auto"
				gap={ 3 }
			>
				<Text fontSize="lg" fontWeight="bold">
					{ sprintf(
						//translate: %s question title
						__( '%s', 'quizpress' ),
						question?.question_title
					) }
				</Text>
				<Text m={ 0 }>
					{ sprintf(
						//translate: %s question description
						__( '%s', 'quizpress' ),
						question?.question_content
					) }
				</Text>
			</Flex>

			{ renderSwitchQuestionType( question?.question_type ) }

			<Flex justify="space-between" mt={ 6 }>
				<Button
					onClick={ handlePrev }
					disabled={ currentStepIndex === 0 }
					{ ...primaryBtn }
				>
					{ __( 'Previous' ) }
				</Button>

				{ isLastStep ? (
					<Flex gap={ 3 } alignItems="center">
						<Button
							{ ...primaryBtn }
							onClick={ () => {
								if ( isAnswerRequired && ! isAnswered ) {
									dispatch(
										showNotification( {
											message: __(
												'Answer of this question is required',
												'quizpress'
											),
											isShow: true,
											type: 'error',
										} )
									);
									return;
								}
								submitAnswer( false );
								handleSubmit();
							} }
						>
							{ __( 'Submit' ) }
						</Button>
					</Flex>
				) : (
					<Flex gap={ 3 } alignItems="center">
						{ ! isAnswerRequired && (
							<Button
								{ ...outlineBtn }
								onClick={ () => {
									handleNext();
								} }
							>
								{ __( 'Skip' ) }
							</Button>
						) }
						<Button
							{ ...primaryBtn }
							onClick={ () => {
								if ( isAnswerRequired && ! isAnswered ) {
									dispatch(
										showNotification( {
											message: __(
												'Answer of this question is required',
												'quizpress'
											),
											isShow: true,
											type: 'error',
										} )
									);
									return;
								}
								submitAnswer( true );
							} }
						>
							{ __( 'Next' ) }
						</Button>
					</Flex>
				) }
			</Flex>
		</Flex>
	);
};

export default QuizAnswer;
