import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Formik } from 'formik';
import TopBar from '@QPComponents/TopBar';
import QPLabel from '@QPComponents/Labels/QPLabel';
import { primaryBtn } from '../../../../../../assets/scss/chakra/recipe';
import { Button } from '@chakra-ui/react';
import { getInitialValue } from './helper';
import { useDispatch, useSelector } from 'react-redux';
import {
	createQuestion,
	fetchQuestionById,
	updateQuestion,
	updateQuestionAnswerManually,
} from '@QPRedux/Slices/quizQuestionSlice/quizQuestionSlice';
import {
	createAnswer,
	deleteAnswer,
	updateAnswer,
} from '@QPRedux/Slices/quizQuestionSlice/answerActions';
import { useNavigate } from 'react-router-dom';
import { route_path } from '@QPUtils/helper';
import FormInner from './FormInner';
import Preloader from '@QPComponents/Loader/Preloader';

const QuestionOperation = ( { id } ) => {
	const { data: questions, answers } = useSelector(
		( state ) => state.questions
	);
	const [ loading, setLoading ] = useState( true );

	const dispatch = useDispatch();
	const navigate = useNavigate();

	useEffect( () => {
		if ( id && ! questions?.length ) {
			setLoading( true );
			dispatch( fetchQuestionById( id ) ).then( () =>
				setLoading( false )
			);
		}
	}, [ id ] );

	const handleOnSubmit = async ( values, { setSubmitting } ) => {
		const { answers: submittedAnswers, ...rest } = values;

		const newQstPayload = {
			...rest,
		};

		const handleAnswers = async ( question_id ) => {
			const deletePromises = [];
			const updateOrCreatePromises = [];

			const existingAnswers = answers?.data || [];

			// Prepare deletions
			existingAnswers.forEach( ( existing ) => {
				const stillExists = submittedAnswers.some(
					( a ) =>
						Number( a?.answer_id ) === Number( existing?.answer_id )
				);
				if ( ! stillExists ) {
					deletePromises.push(
						dispatch( deleteAnswer( existing.answer_id ) )
					);
				}
			} );

			// Prepare updates or creations
			submittedAnswers.forEach( ( answer ) => {
				const action = answer?.answer_id ? updateAnswer : createAnswer;
				updateOrCreatePromises.push(
					dispatch(
						action( {
							...answer,
							question_id,
						} )
					)
				);
			} );

			// Wait for all actions to complete
			const results = await Promise.all( [
				...deletePromises,
				...updateOrCreatePromises,
			] );

			// Extract and return final payloads (actual answers)
			return results.map( ( r ) => r.payload || r );
		};
		setSubmitting( true );

		if ( rest?.question_id ) {
			await handleAnswers( rest?.question_id );
			dispatch( updateQuestion( newQstPayload ) )
				.then( async () => {} )
				.finally( () => {
					setSubmitting( false );
				} );

			return;
		}

		// Create new question
		dispatch( createQuestion( newQstPayload ) )
			.then( async ( { payload } ) => {
				navigate(
					`${ route_path }admin.php?page=quizpress-question&path=question&action=edit&id=${ payload.question_id }`
				);
				const promises = await handleAnswers( payload.question_id );
				dispatch(
					updateQuestionAnswerManually( {
						questionId: payload.question_id,
						answers: promises,
					} )
				);

				await Promise.all( promises );
			} )
			.finally( () => {
				setSubmitting( false );
			} );
	};

	return (
		<>
			{ loading ? (
				<Preloader />
			) : (
				<Formik
					enableReinitialize
					initialValues={ getInitialValue( id, questions ) }
					onSubmit={ handleOnSubmit }
				>
					{ ( { values, handleSubmit, isSubmitting, dirty } ) => {
						return (
							<div className="quizpress-page-content--questions">
								<TopBar
									leftContent={ () => (
										<>
											<span className="quizpress-topbar-logo quizpress-icon quizpress-icon--quizpress" />
											<span className="quizpress-icon quizpress-icon--angle-right quizpress-muted" />
											<QPLabel
												as="h2"
												color="#4F46E5"
												type="subtitle"
												fontWeight="medium"
												label={ __(
													'Questions',
													'quizpress'
												) }
												href={ `${ route_path }admin.php?page=quizpress-question` }
											/>
											<span className="quizpress-icon quizpress-icon--angle-right quizpress-muted" />
											<QPLabel
												as="h2"
												color="#4F46E5"
												type="subtitle"
												fontWeight="medium"
												label={ __(
													values?.question_title ??
														'New Question',
													'quizpress'
												) }
											/>
										</>
									) }
									rightContent={ () => (
										<Button
											{ ...primaryBtn }
											onClick={ handleSubmit }
											disabled={ ! dirty || isSubmitting }
											loading={ isSubmitting }
										>
											{ __(
												id ? 'Update' : 'Create',
												'quizpress'
											) }
										</Button>
									) }
								/>

								<FormInner />
							</div>
						);
					} }
				</Formik>
			) }
		</>
	);
};

export default QuestionOperation;
