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

const ImageTextAnswer = ( {
	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 ) => (
							<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)',
										} }
										border="2px solid var(--quizpress-primary)"
										borderRadius="full"
										boxSize="20px"
										bg="white"
										position="absolute"
										top="8px"
										right="8px"
									/>
									<Image
										src={ imageMap[ ans.image_id ] }
										alt={ ans?.answer_title }
										height="250px"
										width="250px"
										objectFit="cover"
										borderRadius="md"
									/>
									<Text
										p={ 2 }
										fontSize="sm"
										fontWeight="medium"
										color="var(--quizpress-font-color)"
									>
										{ ans?.answer_title }
									</Text>
								</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"
										display="inline-block"
									>
										<Checkbox.HiddenInput />
										<Checkbox.Control
											_checked={ {
												bg: 'var(--quizpress-primary)',
												borderColor:
													'var(--quizpress-primary)',
											} }
											border="2px solid var(--quizpress-primary)"
											borderRadius="md"
											boxSize="20px"
											bg="white"
											position="absolute"
											top="8px"
											right="8px"
										/>
										<Image
											src={ imageMap[ ans.image_id ] }
											alt={ ans?.answer_title }
											height="250px"
											width="250px"
											objectFit="cover"
											borderRadius="md"
										/>
										<Text
											p={ 2 }
											fontSize="sm"
											fontWeight="medium"
											color="var(--quizpress-font-color)"
										>
											{ ans?.answer_title }
										</Text>
									</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 ImageTextAnswer;
