import { select } from '@wordpress/data';
import { useState, useEffect } from 'react';
import Fetch from '../../helpers/fetch';
import ContentImprovementIdeas from './content-improvement-ideas';
import ContentInfoSidebarSection from './content-info';

const ContentInfoAndContentGaps = () => {
    const [mainIntent, setMainIntent] = useState(null);
    const [targetAudience, setTargetAudience] = useState(null);
    const [suggestions, setSuggestions] = useState([]);
    const [isScanning, setIsScanning] = useState(true);

    const fetchImprovementInfo = (postId) => {
        Fetch.get(`sidebar/${postId}/content-improvement-ideas`, (res) => {
            setMainIntent(res?.data?.intents ?? '');
            setTargetAudience(res?.data?.audience ?? '');
            setSuggestions(res?.data?.suggestions ?? {});
            setIsScanning(res?.data?.isScanning ?? false);
        });
    };

    useEffect(() => {
        const post = select('core/editor').getCurrentPost();
        const postId = post.id;

        fetchImprovementInfo(postId);

        const interval = setInterval(() => {
            Fetch.get(`sidebar/${postId}/content-improvement-ideas/status`, (res) => {
                const scanning = res?.data?.isScanning;

                if (!scanning) {
                    clearInterval(interval);
                    fetchImprovementInfo(postId);
                }
            });
        }, 3000);

        return () => clearInterval(interval);
    }, []);

    return (
        <>
            <ContentInfoSidebarSection
                mainIntent={mainIntent}
                targetAudience={targetAudience}
            />
            <ContentImprovementIdeas
                suggestions={suggestions}
                isScanning={isScanning}
            />
        </>
    );
};

export default ContentInfoAndContentGaps;
