import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import ReactModalFormik from '@QPComponents/Modal/ReactModalFormik';
import FormInner from './FormInner';
import { useDispatch } from 'react-redux';
import { useFormikContext } from 'formik';
import { updateQuiz } from '@QPRedux/Slices/quizSlice/quizSlice';
import { API, namespace } from '@QPUtils/helper';
import { handleUpdateQuestionOrder, makeQstMeta } from '../../helper';

const QuestionImport = ( { isOpen, onRequestClose } ) => {
	const { setFieldValue, values: quizValues } = useFormikContext();
	const [ loading, setLoading ] = useState( false );
	const [ filterData, setFilterData ] = useState( [] );
	const [ questions, setQuestions ] = useState( {
		data: [],
		totalItems: 0,
		currentPage: 1,
	} );
	const rowsPerPage = 10;

	const handleDefaultChange = ( id, e ) => {
		if ( e.checked ) {
			setFilterData( ( prev ) => [ ...prev, Number( id ) ] );
		} else {
			setFilterData( ( prev ) =>
				prev.filter( ( item ) => Number( item ) !== Number( id ) )
			);
		}
	};

	const dispatch = useDispatch();

	const fetchQuestions = async ( page = 1, perPage = rowsPerPage ) => {
		setLoading( true );
		try {
			const response = await API.get( `${ namespace }questions`, {
				params: { page, per_page: perPage, status: 'publish' },
			} );
			const totalFromHeader =
				Number( response.headers[ 'x-wp-total' ] ) || 0;

			setQuestions( ( prev ) => ( {
				data: [ ...prev.data, ...response.data ],
				totalItems: totalFromHeader,
				currentPage: page,
			} ) );
		} catch ( error ) {
			console.error( 'Error fetching questions:', error );
		} finally {
			setLoading( false );
		}
	};

	useEffect( () => {
		if ( questions.data.length <= 1 ) {
			fetchQuestions( 1 );
		}
	}, [] );

	useEffect( () => {
		const initial = ( quizValues?.questions || [] ).map( ( q ) =>
			Number( q.question_id )
		);
		setFilterData( initial );
	}, [ quizValues ] );

	const handleSubmit = ( values, { setSubmitting } ) => {
		if ( filterData.length === 0 ) {
			setSubmitting( false );
			onRequestClose();
			return;
		}

		const importableQsts = questions.data.filter(
			( qst ) =>
				filterData.includes( Number( qst.question_id ) ) &&
				quizValues.questions.every(
					( q ) =>
						Number( q.question_id ) !== Number( qst.question_id )
				)
		);

		const updated = [ ...quizValues.questions, ...importableQsts ];

		const updatedQuestions = updated.map( ( q, i ) => ( {
			...q,
			question_order: i + 1,
		} ) );

		setFieldValue( 'questions', updatedQuestions );
		setSubmitting( false );
		dispatch(
			updateQuiz( {
				params: {
					...quizValues,
					meta: {
						...quizValues?.meta,
						quizpress_quiz_questions:
							makeQstMeta( updatedQuestions ),
					},
				},
				questions: updatedQuestions,
			} )
		);
		const newQstOrderPayload = updatedQuestions.map( ( q ) => ( {
			question_id: q.question_id,
			question_order: q.question_order,
		} ) );
		handleUpdateQuestionOrder( quizValues, newQstOrderPayload );
	};

	return (
		<ReactModalFormik
			title={ __( 'Import Questions', 'quizpress' ) }
			isOpen={ isOpen }
			onRequestClose={ onRequestClose }
			isEnabledFooter={ true }
			isEnabledResizer={ false }
			submitButtonLabel={ __( 'Import', 'quizpress' ) }
			cancelButtonLabel={ __( 'Cancel', 'quizpress' ) }
			formik={ {
				enableReInitialize: true,
				initialValues: {
					qsts: questions.data.map( ( qst ) => qst.question_id ),
					quiz_filter: '',
					question_type_filter: '',
					answer_type_filter: '',
				},
				onSubmit: handleSubmit,
			} }
		>
			<FormInner
				quizValues={ quizValues }
				handleDefaultChange={ handleDefaultChange }
				setFilterData={ setFilterData }
				filterData={ filterData }
				fetchQuestions={ fetchQuestions }
				loading={ loading }
				setLoading={ setLoading }
				questions={ questions }
				setQuestions={ setQuestions }
				rowsPerPage={ rowsPerPage }
			/>
		</ReactModalFormik>
	);
};

export default QuestionImport;
