import React, { useEffect, useState } from 'react';
import { useFormikContext } from 'formik';
import {
	Box,
	Checkbox,
	CheckboxGroup,
	Flex,
	Image,
	RadioGroup,
	Text,
} from '@chakra-ui/react';
import { __ } from '@wordpress/i18n';
import { rest_url } from '@QPUtils/helper';

const ImageAnswer = ( { question, answers, questionType, handleChange } ) => {
	const { values } = useFormikContext();
	const selectedValue = values?.answers?.[ question.question_id ] || '';

	const [ imageMap, setImageMap ] = useState( {} );

	useEffect( () => {
		if ( ! answers?.length ) {
			return;
		}

		const fetchImages = async () => {
			const newMap = {};
			await Promise.all(
				answers.map( async ( ans ) => {
					try {
						const res = await fetch(
							`${ rest_url }wp/v2/media/${ ans.image_id }`
						);
						const data = await res.json();
						newMap[ ans.image_id ] = data.link;
					} catch ( err ) {
						console.error(
							`Failed to fetch image for id ${ ans.image_id }`,
							err
						);
					}
				} )
			);
			setImageMap( newMap );
		};

		fetchImages();
	}, [ answers ] );

	return ! answers.length ? (
		<Text color="gray.500">
			{ __( 'No answers available.', 'quizpress' ) }
		</Text>
	) : (
		<Flex direction="column" gap={ 3 }>
			{ ( questionType === 'single_choice' ||
				questionType === 'single_choice_horizontal' ) && (
				<RadioGroup.Root
					onValueChange={ ( e ) => handleChange( e ) }
					value={ selectedValue[ 0 ] }
				>
					<Flex
						direction={
							questionType === 'single_choice_horizontal'
								? 'row'
								: 'column'
						}
						flexWrap={
							questionType === 'single_choice_horizontal'
								? 'wrap'
								: 'nowrap'
						}
						gap={ 3 }
					>
						{ answers.map( ( ans ) => {
							return (
								<RadioGroup.Item
									key={ ans.answer_id }
									value={ ans.answer_id }
								>
									<Box
										cursor="pointer"
										textAlign="center"
										borderRadius="lg"
										overflow="hidden"
										boxShadow="sm"
										_hover={ { boxShadow: 'md' } }
										transition="all 0.2s"
										position="relative"
									>
										<RadioGroup.ItemHiddenInput />
										<RadioGroup.ItemIndicator
											_checked={ {
												bg: 'var(--quizpress-primary)',
												borderColor:
													'var(--quizpress-primary)',
											} }
											borderRadius="full"
											position="absolute"
											top="8px"
											left="8px"
											right="0"
											zIndex="1"
											boxSize="20px"
											border="2px solid var(--quizpress-primary)"
											bg="white"
										/>
										<img
											as={ Image }
											src={ imageMap[ ans.image_id ] }
											height="250px"
											width="250px"
										/>
										<RadioGroup.ItemText>
											{ ans.answer_title }
										</RadioGroup.ItemText>
									</Box>
								</RadioGroup.Item>
							);
						} ) }
					</Flex>
				</RadioGroup.Root>
			) }
			{ ( questionType === 'multiple_choice' ||
				questionType === 'multiple_choice_horizontal' ) && (
				<Checkbox.Root
					onValueChange={ ( e ) => handleChange( e ) }
					value={ selectedValue }
				>
					<Flex
						direction={
							questionType === 'multiple_choice_horizontal'
								? 'row'
								: 'column'
						}
						flexWrap={
							questionType === 'multiple_choice_horizontal'
								? 'wrap'
								: 'nowrap'
						}
						gap={ 3 }
					>
						<CheckboxGroup>
							{ answers.map( ( ans ) => (
								<Checkbox.Root
									key={ ans.answer_id }
									value={ ans.answer_id }
								>
									<Box
										cursor="pointer"
										textAlign="center"
										borderRadius="lg"
										overflow="hidden"
										boxShadow="sm"
										_hover={ { boxShadow: 'md' } }
										transition="all 0.2s"
										position="relative"
									>
										<Checkbox.HiddenInput />
										<Checkbox.Control
											_checked={ {
												bg: 'var(--quizpress-primary)',
												borderColor:
													'var(--quizpress-primary)',
											} }
											position="absolute"
											top="8px"
											left="8px"
											right="0"
											zIndex="1"
											boxSize="20px"
											border="2px solid var(--quizpress-primary)"
											bg="white"
										/>
										<Image
											src={ imageMap[ ans.image_id ] }
											height="250px"
											width="250px"
										/>
										<Checkbox.Label>
											{ ans.answer_title }
										</Checkbox.Label>
									</Box>
								</Checkbox.Root>
							) ) }
						</CheckboxGroup>
					</Flex>
				</Checkbox.Root>
			) }
			{ /* {questionType === 'drop_down' &&
				<Select
					onChange={handleChange}
					value={
						answers
							.map((item) => ({ label: item.answer_title, value: item.answer_id }))
							.find((opt) => opt.value === selectedValue) || null
					}
					options={answers.map((item) => ({
						label: item.answer_title,
						value: item.answer_id,
					}))}
					placeholder={__('Select an option', 'quizpress')}
				/>
			} */ }
		</Flex>
	);
};
export default ImageAnswer;
