import { __ } from '@wordpress/i18n';
import { useState, useEffect } from 'react';
import { dispatch, select } from '@wordpress/data';
import { rawHandler } from '@wordpress/blocks';
import { __experimentalText as Text } from '@wordpress/components';
import SidebarSpinner from './sidebar-spinner';
import ImprovementTextModal from './improvement-text-modal';
import SidebarSection from '../sidebar-section';
import SidebarNotification from './sidebar-notification';
import Fetch from '../../helpers/fetch';

const ContentImprovementIdeas = ({ suggestions, isScanning }) => {
    const [isImprovementTextModalShow, setIsImprovementTextModalShow] = useState(false);
    const [postId, setPostId] = useState(0);
    const [improvementText, setImprovementText] = useState('');
    const [improvementGenerating, setImprovementGenerating] = useState(null);

    const openImprovementTextModal = () => setIsImprovementTextModalShow(true);
    const closeImprovementTextModal = () => setIsImprovementTextModalShow(false);

    useEffect(() => {
        const post = select('core/editor').getCurrentPost();
        setPostId(post.id);
    }, []);

    const processImprovementTextResults = (res) => {
        setImprovementText(res.data.generated_content_wo_wrapper);
        openImprovementTextModal();
        setImprovementGenerating(null);
    };

    const generateImprovementText = (post_id, index, type) => {
        setImprovementGenerating(index);

        Fetch.post(`sidebar/${post_id}/content-improvement-ideas/generate`, {
            index_suggestion: index,
            type: type
        }, processImprovementTextResults);
    };

    const addToContent = (html) => {
        const blocks = rawHandler({ HTML: html });
        dispatch('core/block-editor').insertBlocks(blocks);
        closeImprovementTextModal();
    };

    return (
        <SidebarSection title={__("Content Gaps", "seoaic")} id="seoaic_ci_ideas">
            <div className="seoaic-sidebar-suggestions">
                {isScanning ? (
                    <SidebarSpinner />
                ) : suggestions?.content?.length > 0 ? (
                    suggestions.content.map((obj, i) => {
                        const index = i + 2;
                        const linkClassName =
                            "seoaic-suggestion-link seoaic-accent" +
                            (improvementGenerating === index ? ' loading' : '');

                        return (
                            <div className="seoaic-sidebar-suggestion" key={i}>
                                <div className="seoaic-sidebar-suggestion-card">
                                    <Text
                                        variant="title.small"
                                        as="h4"
                                        className="seoaic-suggestion-title"
                                        weight="600"
                                    >
                                        {obj.title}
                                    </Text>
                                    <Text
                                        variant="subtitle"
                                        isBlock={true}
                                        className="seoaic-suggestion-body"
                                    >
                                        {obj.description}
                                    </Text>
                                    <a
                                        className={linkClassName}
                                        href="#"
                                        onClick={(e) => {
                                            e.preventDefault();
                                            generateImprovementText(postId, index, 'content');
                                        }}
                                    >
                                        {improvementGenerating === index
                                            ? __('Generating', 'seoaic')
                                            : __('Generate example text', 'seoaic')}
                                    </a>
                                </div>
                            </div>
                        );
                    })
                ) : (
                    <SidebarNotification type="info">
                        {__("Nothing here.", "seoaic")}
                    </SidebarNotification>
                )}

                {isImprovementTextModalShow && (
                    <ImprovementTextModal
                        improvementText={improvementText}
                        closeImprovementTextModal={closeImprovementTextModal}
                        addToContent={addToContent}
                    />
                )}
            </div>
        </SidebarSection>
    );
};

export default ContentImprovementIdeas;
