import { __ } from '@wordpress/i18n';
import { useState } from 'react';
import { dispatch } from '@wordpress/data';
import { useBlockProps, InspectorControls, BlockControls } from '@wordpress/block-editor';
import { ToolbarGroup, ToolbarButton, TextareaControl, PanelBody, Button } from "@wordpress/components";
import Fetch from '../../content-editor/helpers/fetch';
import GenerateImagesBlock from './components/generate-images-block';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './editor.scss';

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
    const [ userPrompt, setUserPrompt ] = useState("");
    const [ generatedImages, setGeneratedImages ] = useState([]);
    const [ selectedImg, setSelectedImg ] = useState(false);
    const [ isGeneratingAlt, setIsGeneratingAlt ] = useState(false);

    const noticesDispatcher = dispatch('core/notices');

    const regenerateImage = () => {
        setGeneratedImages([]);
    };

    const generateAltTextCallback = (resp) => {
        setAttributes({
            alt: resp?.data?.alt ?? ""
        });

        setIsGeneratingAlt(false);
    };

    const generateAltText = (callback) => {
        setIsGeneratingAlt(true);
        callback = callback || generateAltTextCallback;

        Fetch.post('blocks/generate-image/generate-alt-text', {
            'image': selectedImg
        }, callback)
        .catch((err) => {
            console.error('[seoaic]:', err.message);

            noticesDispatcher.createErrorNotice(__('Request failed', 'seoaic'), {
                id: 'seoaic-request-failed',
                isDismissible: true,
                type: 'snackbar',
            });

            setIsGeneratingAlt(false);
        });
    };

    const onChangeAltField = (value) => {
        setAttributes({
            alt: value
        });
    };

    const regenerateAltClickHandler = () => {
        generateAltText();
    };

    return (
        <div { ...useBlockProps() }>
            <GenerateImagesBlock
                attributes={ attributes }
                generatedImages={ generatedImages }
                setGeneratedImages={ setGeneratedImages }
                selectedImg={ selectedImg }
                setSelectedImg={ setSelectedImg }
                userPrompt={ userPrompt }
                setUserPrompt={ setUserPrompt }
                generateAltText={ generateAltText }
            />
            { (0 != generatedImages.length || attributes.url) && <BlockControls>
                <ToolbarGroup>
                    <ToolbarButton
                        showTooltip
                        icon="update-alt"
                        label={ __("Reset generated images", "seoaic") }
                        onClick={ regenerateImage }
                    />
                </ToolbarGroup>
            </BlockControls> }
            { (attributes.url)
            && <InspectorControls key="setting">
                <PanelBody>
                    <TextareaControl
                        label={ __('Alternative text', 'seoaic') }
                        rows={3}
                        value={ attributes.alt }
                        onChange={ onChangeAltField }
                    />
                    <Button
                        variant="secondary"
                        size="small"
                        onClick={ regenerateAltClickHandler }
                        isBusy={ isGeneratingAlt }
                    >{ __("Regenerate Alt text", "seoaic") }</Button>
                </PanelBody>
            </InspectorControls> }
        </div>
    );
}
