import { useState, useEffect } from 'react';
import { useDispatch, dispatch } from '@wordpress/data';
import { loadPluginSidebar } from '../../utils/loadPluginSidebar';
import SearchConsoleSidebarSection from './search-console';
import CompetitorsSidebarSection from './competitors';
import ContentInfoAndContentGaps from './content-info-and-content-gaps';
import MetaDescriptionSidebarSection from './meta-description';
import InternalLinksSidebarSection from './internal-links';
import InteractiveArticleStatsSidebarSection from './interactive-article-stats';
import Fetch from "../../helpers/fetch";

const SEOAICSidebar = () => {

    const [ PluginSidebar, setPluginSidebar ] = useState(null)
    const [ fetchedKeywords, setFetchedKeywords ] = useState([]);
    const [ areKeywordsFetched, setAreKeywordsFetched ] = useState(false);
    const { setImageCredit } = useDispatch('SEOAIBlocks');
    const dispatcher = dispatch('core/edit-post');

    useEffect(() => {
        const fetchPluginSidebar = async () => {
            try {
                const { PluginSidebar } = await loadPluginSidebar();
                setPluginSidebar(() => PluginSidebar);

                const urlParams = new URLSearchParams(window.location.search);
                const showSidebar = urlParams.get('content-improvement') === 'true';

                if (showSidebar) {
                    dispatcher.openGeneralSidebar('seoaic-gutenberg-sidebar-plugin/seoaic-gutenberg-sidebar');
                }
            } catch (error) {
                console.error('Error loading PluginSidebar:', error);
            }
        };

        getImageCredit();
        fetchPluginSidebar();
    }, []);

    const getImageCredit = async () => {
        await Fetch.get('options/image_credits', (res) => {
            const {seoaic_images_credit, seoaic_images_credit_limit} = res.data.data;

            setImageCredit({
                seoaic_images_credit,
                seoaic_images_credit_limit,
            });
        })
        .catch((err) => {
            console.error('[seoaic]:', err.message);
        });
    };

    if (!PluginSidebar) {
        return <div>Loading...</div>;
    }

    return (
        <PluginSidebar
            name="seoaic-gutenberg-sidebar"
            title="SEO AI"
            icon="screenoptions seoaic-icon"
        >
            <SearchConsoleSidebarSection
                setFetchedKeywordsHandler={ (value) => {
                    setFetchedKeywords(value);
                } }
                setIsKeywordsDataFetchedHandler={ (value) => {
                    setAreKeywordsFetched(value);
                } }
            />
            <CompetitorsSidebarSection
                areKeywordsFetched={ areKeywordsFetched }
                keywords={ fetchedKeywords }
            />
            <ContentInfoAndContentGaps/>
            <MetaDescriptionSidebarSection/>
            <InternalLinksSidebarSection/>
            <InteractiveArticleStatsSidebarSection/>
        </PluginSidebar>
    );
}

export default SEOAICSidebar;
