import { __ } from '@wordpress/i18n';
import { useEffect, useState } from 'react';
import { Flex, FlexBlock, __experimentalText as Text } from '@wordpress/components';
import ImageBlockSpinner from './image-block-spinner';

const GeneratedImages = ({ isGenerating, generatedImages, setSelectedImg }) => {
    const [ selectedIndex, setSelectedIndex ] = useState(false);

    const selectImageHandler = (generatedImage, index) => {
        setSelectedImg(generatedImage);
        setSelectedIndex(index);
    };

    useEffect(() => {
        if (
            generatedImages.length
            && 1 == generatedImages.length
        ) {
            setSelectedImg(generatedImages[0]);
            setSelectedIndex(0);
        } else {
            setSelectedIndex(false);
        }
    }, [generatedImages]);

    return (
        <>
            {
                1 < generatedImages.length
                && <Text
                    variant="subtitle"
                    isBlock="true"
                    className="seoaic-field-title"
                >
                    { __("Choose the image.", "seoaic") }
                </Text>
            }
            <Flex
                className="seoaic-generated-images"
                gap={2}
                align="center"
                justify="left"
            >
                {
                    0 < generatedImages.length
                    && generatedImages.map((generatedImage, index) => {
                        return <FlexBlock
                            className={ "seoaic-generated-image-wrapper" + (index === selectedIndex ? ' selected' : '') }
                            onClick={ () => {
                                selectImageHandler(generatedImage, index)
                            } }
                        >
                            <img src={ generatedImage.url }/>
                        </FlexBlock>;
                    })
                // : <FlexBlock>{ __("No images generated", "seoaic") }</FlexBlock>
                }
                { isGenerating &&
                    <FlexBlock>
                        <ImageBlockSpinner/>
                    </FlexBlock>
                }
            </Flex>
        </>
    );
};

export default GeneratedImages;