import {__} from '@wordpress/i18n';
import {useState, useEffect} from 'react';
import {select, useSelect, useDispatch} from '@wordpress/data';
import {store as noticesStore} from '@wordpress/notices';
import {TextareaControl, RangeControl, SelectControl} from '@wordpress/components';
import GradientButton from '../../../blocks/generate-image/components/gradient-button';
import Fetch from '../../helpers/fetch';

const ThumbnailGenerator = () => {
    const {getCurrentPostId} = select("core/editor");
    const {
        editPost,
        lockPostSaving,
        lockPostAutosaving,
        unlockPostSaving,
        unlockPostAutosaving
    } = useDispatch("core/editor");
    const {createSuccessNotice, createErrorNotice} = useDispatch(noticesStore);
    const THUMBNAIL_PROMPT_META_KEY = 'thumbnail_generate_prompt';
    const THUMBNAIL_GENERATED_META_KEY = 'thumbnail_generated';
    const meta = useSelect((select) =>
        select('core/editor').getEditedPostAttribute('meta')
    );

    const metaThumbnailPrompt = meta ? meta[THUMBNAIL_PROMPT_META_KEY] : '';
    const metaThumbnailGenerated = meta ? meta[THUMBNAIL_GENERATED_META_KEY] : '';
    const [isGenerating, setIsGenerating] = useState(false);
    const [thumbnailPrompt, setThumbnailPrompt] = useState('');
    const imageCredit = useSelect((select) =>
        select('SEOAIBlocks').getImageCredit()
    );
    const [width, setWidth] = useState(1024);
    const [height, setHeight] = useState(768);
    const [style, setStyle] = useState('Photorealism');

    useEffect(() => {
        if (!metaThumbnailGenerated) {
            Fetch.get('options/seoaic_options/seoaic_image_generate_prompt_default', (res) => {
                setThumbnailPrompt(res.data.value);
            });
        } else {
            setThumbnailPrompt(metaThumbnailPrompt);
        }

        Fetch.get('options/seoaic_options/seoaic_image_generate_width_default', (res) => {
            const val = parseInt(res.data.value, 10);
            setWidth(!isNaN(val) ? val : 1024);
        });

        Fetch.get('options/seoaic_options/seoaic_image_generate_height_default', (res) => {
            const val = parseInt(res.data.value, 10);
            setHeight(!isNaN(val) ? val : 768);
        });

        Fetch.get('options/seoaic_options/seoaic_image_generate_style', (res) => {
            const val = res.data.value;
            setStyle(val);
        });

    }, [metaThumbnailGenerated, metaThumbnailPrompt]);

    const setDefaultPrompt = () => {
        Fetch.get('options/seoaic_options/seoaic_image_generate_prompt_default', (res) => {
            setThumbnailPrompt(res.data.value);
        });
    };

    const generateThumbnailCallback = (resp) => {
        if (true == resp.success) {
            createSuccessNotice(__('Image generated!', 'seoaic'), {
                id: 'seoaic-image-generated',
                isDismissible: true,
                type: 'snackbar',
            });

            if (resp?.data?.attachment?.id) {
                editPost({featured_media: resp.data.attachment.id});
            } else {
                createErrorNotice(__('No attachment created', 'seoaic'), {
                    id: 'seoaic-request-failed',
                    isDismissible: true,
                    type: 'snackbar',
                });
            }

        } else {
            const errMsg = resp?.message ?? __('No attachment created', 'seoaic');

            createErrorNotice(errMsg, {
                id: 'seoaic-request-failed',
                isDismissible: true,
                type: 'snackbar',
            });
        }
    };

    const generateThumbnail = (postID) => {
        lockPostSaving('process-remote');
        lockPostAutosaving('process-remote');
        setIsGenerating(true);

        Fetch.post('post/' + postID + '/thumbnail-generate', {
            'prompt': thumbnailPrompt,
            'style': style,
            'width': width,
            'height': height
        }, generateThumbnailCallback)
            .catch((err) => {
                console.error('[seoaic]:', err.message);

                createErrorNotice(__('Request failed', 'seoaic'), {
                    id: 'seoaic-request-failed',
                    isDismissible: true,
                    type: 'snackbar',
                });
            })
            .finally(() => {
                setIsGenerating(false);
                unlockPostSaving('process-remote');
                unlockPostAutosaving('process-remote');
            });
    };

    return (
        <>
            <TextareaControl
                label={__("Prompt", "seoaic")}
                help={(
                    <>
                        {__("Optional field. Use prompt to specify more precise results of image generation.", "seoaic")}
                        <br/>
                        <strong>
                        {
                            (imageCredit.seoaic_images_credit && imageCredit.seoaic_images_credit_limit) ? (
                                <span>
                                    {imageCredit.seoaic_images_credit} {__('out of', 'seoaic')} {imageCredit.seoaic_images_credit_limit} {__('images left', 'seoaic')}
                                </span>
                            ) : (
                                <span>
                                    {__('Loading image credit...', 'seoaic')}
                                </span>
                            )
                        }
                        </strong>
                    </>
                )}
                value={thumbnailPrompt}
                onChange={(newValue) => setThumbnailPrompt(newValue)}
            />
            {
                !meta
                    ? (
                        <div className="seoaic-thumbnail-default-prompt-note seoaic-warning-note seoaic-mb-10">
                            {__("Note: enable the Custom Fields option if you're using custom post type.", "seoaic")}
                        </div>
                    )
                    : ''
            }
            <div
                className="seoaic-thumbnail-default-prompt-wrapper seoaic-mb-10"
            >
                <a
                    href="#"
                    onClick={setDefaultPrompt}

                >{__("Use default prompt", "seoaic")}</a>
            </div>

            <SelectControl
                label="Choose a style"
                value={ style }
                name="thumbnail_style"
                options={ [
                    { label: 'Illustrations', value: 'Illustrations' },
                    { label: 'Photorealism', value: 'Photorealism' },
                    { label: 'Digital art', value: 'Digital art' },
                    { label: 'Minimalism', value: 'Minimalism' },
                    { label: 'Collages', value: 'Collages' },
                ] }
                onChange={(newStyle) => setStyle(newStyle)}
            />
            <RangeControl
                label="Width"
                value={width}
                step={32}
                name="thumbnail_width"
                onChange={(newWidth) => setWidth(newWidth)}
                min={256}
                max={1440}
            />
            <RangeControl
                label="Height"
                value={height}
                step={32}
                name="thumbnail_height"
                onChange={(newHeight) => setHeight(newHeight)}
                min={256}
                max={1440}
            />
            <GradientButton
                label={__("Generate featured image", "seoaic")}
                isBusy={isGenerating}
                onClick={() => {
                    editPost({
                        meta: {
                            ...meta,
                            [THUMBNAIL_PROMPT_META_KEY]: thumbnailPrompt,
                            [THUMBNAIL_GENERATED_META_KEY]: true
                        },
                    });
                    generateThumbnail(getCurrentPostId());
                }}
            />
        </>
    );
};

export default ThumbnailGenerator;
