import { __ } from '@wordpress/i18n';
import { dispatch, select } from '@wordpress/data';
import { ExternalLink } from '@wordpress/components';
import { useState, useEffect } from 'react';
import Fetch from '../../helpers/fetch';
import SearchConsoleTable from './search-console-table';
import SidebarSpinner from './sidebar-spinner';
import SidebarSection from '../sidebar-section';

const SearchConsoleSidebarSection = (props) => {
    const [ ciLink, setCILink] = useState("");
    const [ keywords, setKeywords ] = useState([]);
    const [ isDataFetched, setDataFetched ] = useState(false);
    const count = 10;
    const processResults = (res) => {
        setDataFetched(true);
        props.setIsKeywordsDataFetchedHandler(true);

        if (res.data) {
            setKeywords(res.data);
            props.setFetchedKeywordsHandler(res.data);
        }
    };

    useEffect(() => {
        const post = select('core/editor').getCurrentPost();
        setCILink("admin.php?page=seoaic-content-improvement&search=" + post.title);

        Fetch.get('sidebar/' + post.id + '/top-keywords?count=' + count , processResults);
    }, []);

    return (
        <SidebarSection
            title={ __("Search Console", "seoaic") }
            id="seoaic_search_console"
        >
            {isDataFetched ? (
                keywords.length ? (
                    <>
                        <SearchConsoleTable keywords={ keywords }/>
                        <ExternalLink href={ ciLink }>{ __('See all Keywords', 'seoaic') }</ExternalLink>
                    </>
                ) : (
                    <ExternalLink href={ "admin.php?page=seoaic-settings" }>{ __('Check GSC integration settings', 'seoaic') }</ExternalLink>
                )
            ) : (
                <SidebarSpinner />
            )}
        </SidebarSection>
    );
};

export default SearchConsoleSidebarSection;