import React from 'react';
import { __ } from '@wordpress/i18n';
import { Circle, Flex, Input, Span, Text } from '@chakra-ui/react';
import GstText from '@QPComponents/GstText.js';
import { Field, FieldArray, useFormikContext } from 'formik';
import { getInitialAnswerValue } from '../../containers/BackendDashboard/pages/Quizzes/newQuiz/helper';
import CustomSwitch from '@QPComponents/CustomSwitch';

export default function SequentBlanks( { ansName, ansVal } ) {
	const { setFieldValue, values } = useFormikContext();

	const renderLayout = ( { item, index: ansIndex, self, push, remove } ) => {
		return (
			<Flex gap={ 3 } alignItems="center">
				{ self.length > 1 && (
					<Span
						className="quizpress-icon quizpress-icon--close-red"
						cursor="pointer"
						onClick={ () => remove( index ) }
					/>
				) }
				<Circle
					border="1px solid #22A06B"
					padding="4px"
					cursor="pointer"
					onClick={ () => push( getInitialAnswerValue ) }
				>
					<Span
						className="quizpress-icon quizpress-icon--plus"
						_before={ { color: '#22A06B' } }
					/>
				</Circle>
				<Field
					as={ Input }
					name={ `${ ansName }.${ ansIndex }.answer_title` }
					defaultValue={ item.answer }
					placeholder={ __( 'Enter answer', 'quizpress' ) }
					className="quizpress-input"
				/>
				<Flex
					gap={ 2 }
					alignItems="center"
					p={ 2 }
					border="1px solid var(--quizpress-border-color)"
					borderRadius="4px"
				>
					<Text fontWeight={ 500 } className="quizpress-title">
						{ __( 'Correct', 'quizpress' ) }
					</Text>
					<CustomSwitch
						name={ `${ ansName }.${ ansIndex }.is_correct` }
						value={ Boolean( item.is_correct ) }
						onChange={ ( e ) => {
							setFieldValue(
								`${ ansName }.${ ansIndex }.is_correct`,
								e.target.checked
							);
						} }
					/>
				</Flex>
			</Flex>
		);
	};

	return (
		<Flex flexDirection="column" gap={ 6 }>
			<GstText
				label={ __(
					'Place the {Dash} variable in the description field to render input boxes.',
					'quizpress'
				) }
			/>
			<FieldArray name={ ansName }>
				{ ( { push, remove } ) => {
					return ! ansVal?.length ? (
						<GstText
							type="warning"
							label={ __(
								'No answers found. Please add answers.',
								'quizpress'
							) }
							showBorder={ true }
						/>
					) : (
						ansVal?.map( ( item, ansIndex, self ) =>
							renderLayout( {
								item,
								index: ansIndex,
								self,
								push,
								remove,
							} )
						)
					);
				} }
			</FieldArray>
		</Flex>
	);
}
