import React, { useState } from 'react';
import { Flex, Input, Text } from '@chakra-ui/react';

const ReadOnlyBlanks = ( { question, handleChange } ) => {
	const answerTemplate = question.answers[ 0 ].answer_title;
	const parts = answerTemplate.split( '{dash}' );

	const [ blankValues, setBlankValues ] = useState(
		Array( parts.length - 1 ).fill( '' )
	);

	const buildSentence = ( updated ) => {
		let out = '';
		parts.forEach( ( p, i ) => {
			out += p;
			if ( i < updated.length ) {
				out += updated[ i ];
			}
		} );
		return out.trim();
	};

	const handleBlankChange = async ( index, value ) => {
		const updated = [ ...blankValues ];
		updated[ index ] = value;
		setBlankValues( updated );

		const fullSentence = buildSentence( updated );

		handleChange( { value: fullSentence } );
	};

	return (
		<Flex flexWrap="wrap" align="center" gap={ 2 }>
			{ parts.map( ( text, index ) => (
				<Flex key={ index } alignItems="center">
					{ text && <Text>{ text }</Text> }

					{ index !== parts.length - 1 && (
						<Input
							ml="6px"
							shadow="var(--quizpress-shadow)"
							width="160px"
							height="25px"
							className="quizpress-input"
							value={ blankValues[ index ] }
							onChange={ ( e ) =>
								handleBlankChange( index, e.target.value )
							}
						/>
					) }
				</Flex>
			) ) }
		</Flex>
	);
};

export default ReadOnlyBlanks;
