import { __ } from '@wordpress/i18n';
import { useState } from 'react';
import { select, dispatch } from '@wordpress/data';
import { BlockControls } from '@wordpress/block-editor';
import { DropdownMenu, Icon, ToolbarGroup } from '@wordpress/components';
import ImproveContentModal from './components/modal/improve-content.js';
import TranslateModal from './components/modal/translate.js';
import RewriteModal from './components/modal/rewrite.js';
import ChangeToneModal from './components/modal/change-tone.js';
import MakeItMoreModal from './components/modal/make-it-more.js';
import TextComparisonModal from './components/modal/text-comparison.js';

import { execCommand, commands } from './commands.js';

const ControlsText = (props) => {
    const [ isImproveContentOpen, setImproveContentOpen ] = useState(false);
    const [ improvePrompt, setImprovePrompt ] = useState('');
    const [ isTranslateOpen, setTranslateOpen ] = useState(false);
    const [ translateLanguage, setTranslateLanguage ] = useState('');
    const [ isRewriteOpen, setRewriteOpen ] = useState(false);
    const [ isChangeToneOpen, setChangeToneOpen ] = useState(false);
    const [ isMakeItMoreOpen, setMakeItMoreOpen ] = useState(false);
    const [ generatedText, setGeneratedText ] = useState("");
    const [ isShowComparisonModal, setIsShowComparisonModal ] = useState(false);
    const [ isGenerating, setIsGenerating ] = useState(false);
    const [ lastCommand, setLastCommand ] = useState({
        title: '',
        command: '',
        params: {}
    });

    const storageKey = 'editorImprovePromptsHistory';

    const openImproveContentModal = () => setImproveContentOpen(true);
    const closeImproveContentModal = () => setImproveContentOpen(false);
    const openTranslateModal = () => setTranslateOpen(true);
    const closeTranslateModal = () => setTranslateOpen(false);
    const openRewriteModal = () => setRewriteOpen(true);
    const closeRewriteModal = () => setRewriteOpen(false);
    const openChangeToneModal = () => setChangeToneOpen(true);
    const closeChangeToneModal = () => setChangeToneOpen(false);
    const openMakeItMoreModal = () => setMakeItMoreOpen(true);
    const closeMakeItMoreModal = () => setMakeItMoreOpen(false);
    const openComparisonTextModal = () => setIsShowComparisonModal(true);
    const closeComparisonTextModal = () => setIsShowComparisonModal(false);

    const getSelectedBlock = () => select('core/block-editor').getSelectedBlock();
    const blockEditorDispatcher = dispatch('core/block-editor');

    function handlePromptFromImproveContentModal(value) {
        setImprovePrompt(value);
    }

    function handlePromptFromPromptsHistory(value) {
        setImprovePrompt(value);
    }

    function handleLanguageFromTranslateModal(value) {
        setTranslateLanguage(value);
    }

    function handleTranslateFormSubmit() {
        if ("" == translateLanguage) {
            noticesDispatcher.createErrorNotice(__('Language is required', 'seoaic'), {
                id: 'language-required',
                isDismissible: false,
                type: 'snackbar',
            });
            hideNoticeWithTimeout('language-required');

        } else {
            closeTranslateModal();

            handlerOnClick('translate', {
                language: translateLanguage,
            });
        }
    }

    function handleModeFromRewriteModal(value) {
        handlerOnClick('rewrite', {
            audience: value
        });
    }

    function handleToneFromChangeToneModal(value) {
        handlerOnClick('changeTone', {
            tone: value
        });
    }

    function handleStyleFromMakeItMoreModal(value) {
        handlerOnClick('makeItMore', {
            style: value
        });
    }

    function handleImproveContentFormSubmit() {
        const multisiteDomain = new URL(document.location).pathname.split('/')[1];
        const isMultisite = "wp-admin" != multisiteDomain;
        const key = isMultisite ? multisiteDomain : 'all';
        let lastPrompts = localStorage.getItem(storageKey);
        lastPrompts = null === lastPrompts ? {} : JSON.parse(lastPrompts);
        let domainLastPrompts = "undefined" !== typeof lastPrompts[key] ? lastPrompts[key] : [];

        if (-1 == domainLastPrompts.indexOf(improvePrompt)) { // unique only
            domainLastPrompts.unshift(improvePrompt);
            domainLastPrompts = domainLastPrompts.slice(0, 5);
            lastPrompts[key] = domainLastPrompts;
            localStorage.setItem(storageKey, JSON.stringify(lastPrompts));
        }

        // improveContentFormSubmit(improvePrompt, closeImproveContentModal);
        if ("" == improvePrompt) {
            noticesDispatcher.createErrorNotice(__('Prompt is required', 'seoaic'), {
                id: 'seoaic-prompt-required',
                isDismissible: false,
                type: 'snackbar',
            });
            hideNoticeWithTimeout('seoaic-prompt-required');

        } else {
            closeImproveContentModal();

            handlerOnClick('improveContent', {
                prompt: improvePrompt
            });
        }
    }

    const handleWriteMore = () => {
        const selectedBlock = getSelectedBlock();

        const blocks = select('core/editor').getBlocks();
        const blocksReversed = blocks.length ? [...blocks].reverse() : [];
        let pass = false;
        let title = '';

        // use closest sub-title as title only for paragraphs
        if ("core/paragraph" == selectedBlock.name) {
            for (let i = 0, c = blocksReversed.length; i < c; i++) {
                const block = blocksReversed[i];

                if ("undefined" === typeof block.attributes.content) {
                    continue;
                }

                const content = block.attributes.content.originalHTML;

                if (block.clientId == selectedBlock.clientId) {
                    pass = true;
                }

                if (
                    pass
                    && "core/heading" == block.name
                    && "" != content
                ) {
                    title = content;
                    break;
                }
            }
        }

        if ('' == title) {
            const post = select('core/editor').getCurrentPost();
            title = post.title;
        }

        handlerOnClick('writeMore', {
            title: title,
            content: selectedBlock.attributes.content,
        });
    };

    const execCommandCallback = (newVal) => {
        setGeneratedText(newVal);
    };

    const handleAcceptText = () => {
        blockEditorDispatcher.updateBlock(getSelectedBlock().clientId, {
            attributes: {
                content: generatedText
            }
        });
        closeComparisonTextModal();
    };

    const handlerOnClick = (command, params = {}) => {
        setLastCommand({
            title: commands[command].title,
            command: command,
            params: params
        });
        setIsGenerating(true);
        openComparisonTextModal();
        execCommand(command, params, execCommandCallback)
        .then(() => {
            setIsGenerating(false);
        });
    };

    const handleReprompt = () => {
        handlerOnClick(lastCommand.command, lastCommand.params);
    };

    return (
        <BlockControls group="other">
            <ToolbarGroup>
                <DropdownMenu
                    icon={ <Icon
                        icon="screenoptions"
                        className="dashicons-admin-generic"
                    /> }
                    label={ __('SEOAI Commands', 'seoaic') }
                    controls={ [
                        {
                            title: __('Rephrase', 'seoaic'),
                            onClick: () => {
                                handlerOnClick('rephrase');
                            },
                        },
                        {
                            title: __('Shorten', 'seoaic'),
                            onClick: () => {
                                handlerOnClick('shorten');
                            },
                        },
                        {
                            title: __('Simplify', 'seoaic'),
                            onClick: () => {
                                handlerOnClick('simplify');
                            },
                        },
                        {
                            title: __('Paraphrase', 'seoaic'),
                            onClick: () => {
                                handlerOnClick('paraphrase');
                            },
                        },
                        {
                            title: __('Change Tone ...', 'seoaic'),
                            onClick: openChangeToneModal
                        },
                        {
                            title: __('Make it More  ...', 'seoaic'),
                            onClick: openMakeItMoreModal
                        },
                        {
                            title: __('Write More', 'seoaic'),
                            onClick: () => {
                                handleWriteMore();
                            },
                        },
                        {
                            title: __('Translation', 'seoaic'),
                            onClick: openTranslateModal
                        },
                        {
                            title: __('Summary', 'seoaic'),
                            onClick: () => {
                                handlerOnClick('makeSummary');
                            }
                        },
                        {
                            title: __('Improve (custom prompt)', 'seoaic'),
                            onClick: openImproveContentModal
                        },
                        {
                            title: __('Rewrite ...', 'seoaic'),
                            onClick: openRewriteModal
                        },
                        {
                            title: __('Fix Grammar', 'seoaic'),
                            onClick: () => {
                                handlerOnClick('fixGrammar');
                            },
                        },
                    ] }
                />
                { isImproveContentOpen && (
                    <ImproveContentModal
                        promptValue={ improvePrompt }
                        setPrompt={ handlePromptFromImproveContentModal }
                        setLastUsedPrompt={ handlePromptFromPromptsHistory }
                        close={ closeImproveContentModal }
                        submit={ handleImproveContentFormSubmit }
                    />
                ) }
                { isTranslateOpen && (
                    <TranslateModal
                        language={ translateLanguage }
                        onLanguageChange={ handleLanguageFromTranslateModal }
                        close={ closeTranslateModal }
                        submit={ handleTranslateFormSubmit }
                    />
                ) }
                { isRewriteOpen && (
                    <RewriteModal
                        onRewriteModeChange={ handleModeFromRewriteModal }
                        close={ closeRewriteModal }
                    />
                ) }
                { isChangeToneOpen && (
                    <ChangeToneModal
                        onToneChange={ handleToneFromChangeToneModal }
                        close={ closeChangeToneModal }
                    />
                ) }
                { isMakeItMoreOpen && (
                    <MakeItMoreModal
                        onStyleChange={ handleStyleFromMakeItMoreModal }
                        close={ closeMakeItMoreModal }
                    />
                ) }
                { isShowComparisonModal && (
                    <TextComparisonModal
                        originalText={ getSelectedBlock().attributes.content.originalHTML }
                        generatedText={ generatedText }
                        setGeneratedText={ setGeneratedText }
                        isGenerating={ isGenerating }
                        handleAcceptText={ handleAcceptText }
                        handleReprompt={ handleReprompt }
                        handleCloseComparisonTextModal={ closeComparisonTextModal }
                        openImproveContentModal={ openImproveContentModal }
                        lastCommand={ lastCommand }
                    />
                ) }
            </ToolbarGroup>
        </BlockControls>
    );
};

export default ControlsText;