import { __ } from '@wordpress/i18n';
import { useState, useEffect } from 'react';
import { dispatch, select } from '@wordpress/data';
import { useDispatch } from '@wordpress/data';
import { store as noticesStore } from '@wordpress/notices';
import {
    Dashicon,
    Flex,
    FlexItem,
    TextareaControl,
} from '@wordpress/components';
import Fetch from '../../../content-editor/helpers/fetch';
import GradientButton from '../../generate-image/components/gradient-button';

const GenerateFAQ = ({
    attributes,
    setAttributes,
    manualMode,
}) => {
    const [FAQPrompt, setFAQPrompt] = useState("");
    const [isGenerate, setIsGenerate] = useState(false);

    const editorDispatcher = dispatch('core/editor');
    const { createSuccessNotice, createWarningNotice } = useDispatch( noticesStore );
    const post = select('core/editor').getCurrentPost();
    const interval = 5;
    let timerId;

    const checkStatus = function(completeCallback) {
        const completeCallbackFunction = completeCallback || function() {};

        Fetch.get('faq/check-status', (response) => {
            if (response.data.data.status === 'complete') {
                completeCallbackFunction();

                if (
                    response.data.data.done[post.id]
                    && response.data.data.done[post.id].content
                ) {
                    setIsGenerate(false);
                    const content = response.data.data.done[post.id].content;
                    let generatedQuestions = [];

                    content.forEach((element, index) => {
                        generatedQuestions.push({
                            'id': index,
                            'title': element.question,
                            'content': element.answer,
                        });
                    });

                    setAttributes({
                        questions: generatedQuestions,
                        mode: manualMode,
                    });

                    editorDispatcher.autosave();
                    createSuccessNotice(__('Autosaved.', 'seoaic'), {
                        id: 'seoaic-autosaved',
                        isDismissible: true,
                        type: 'snackbar',
                    });

                } else {
                    console.error('[seoaic]: No ID in response:', response);

                    createWarningNotice(__('Something went wrong.', 'seoaic'), {
                        id: 'seoaic-request-failed',
                        isDismissible: true,
                        type: 'snackbar',
                    });
                }
            }
        });
    };

    const formGenerateCallback = (res) => {
        if (res.success) {
            timerId = setInterval(() => {
                checkStatus(() => { clearInterval(timerId); });
            }, interval * 1000);

            if (
                res.message
                && res.message.length
            ) {
                createSuccessNotice(res.message, {
                    id: 'seoaic-generate',
                    isDismissible: true,
                    type: 'snackbar',
                });
            }

        } else {
            setIsGenerate(false);

            if (
                res.message
                && res.message.length
            ) {
                createWarningNotice(res.message, {
                    id: 'seoaic-generate',
                    isDismissible: true,
                    type: 'snackbar',
                });
            }
        }
    };

    const generate = () => {
        setIsGenerate(true);
        const data = {
            post_id: post.id,
            prompt: FAQPrompt,
        };

        Fetch.post('faq/generate', data, formGenerateCallback)
        .catch((err) => {
            setIsGenerate(false);
            console.error('[seoaic]:', err.message);

            createWarningNotice(__('Generation request failed', 'seoaic'), {
                id: 'seoaic-request-failed',
                isDismissible: true,
                type: 'snackbar',
            });
        });
    };

    const getPromptCallback = (res) => {
        const data = res.data;

        setFAQPrompt(data.prompt);
    };

    const resetPostStatus = () => {
        // Fetch.post('leads-form/reset-post-status', {
        //     post_id: post.id,
        // }, formGenerateCallback)
        // .catch((err) => {});
    };

    useEffect(() => {
        Fetch.get('faq/prompt', getPromptCallback)
        .catch((err) => {
            console.error('[seoaic]:', err.message);

            createWarningNotice(__('Request failed', 'seoaic'), {
                id: 'seoaic-request-failed',
                isDismissible: true,
                type: 'snackbar',
            });
        });
    }, []);

    return (
        isGenerate
        ? <Flex
            justify="center"
            align="center"
            gap={ 1 }
        >
            <FlexItem>
                <Dashicon
                    icon="admin-generic"
                    className="seoaic-gear-waiting-animate"
                />
            </FlexItem>
            <FlexItem>{ __("Generating...", "") }</FlexItem>
        </Flex>
        : <>
            <TextareaControl
                label={ __("Prompt", "seoaic") }
                rows={4}
                value={ FAQPrompt }
                onChange={ val => setFAQPrompt(val) }
            />
            <GradientButton
                label={ __("Generate", "seoaic") }
                onClick={ generate }
            />
            <GradientButton
                label={ __("Reset Status", "seoaic") }
                onClick={ resetPostStatus }
                className="seoaic-dn"
            />
        </>
    );
};

export default GenerateFAQ;