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

const InternalLinksSidebarSection = () => {
    const [ internalLinks, setInternalLinks ] = useState(null);

    const processResults = (res) => {
        setInternalLinks(res?.data?.internal_links ?? []);
    };

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

        Fetch.get('sidebar/' + post.id + '/internal-links', processResults);
    }, []);

    return (
        <SidebarSection
            title={ __("Internal Links", "seoaic") }
            id="internal_links"
        >
            { internalLinks
            ? ( 0 < internalLinks.length
                ? internalLinks.map((internalLink, i) => {
                    const link = internalLink.link ?? '#';
                    const title = internalLink.title ?? '';

                    return (
                        <p><ExternalLink href={ link } title={ title }>{ title }</ExternalLink></p>
                    );
                })
                : <SidebarNotification type="info">{ __("No internal links.", "seoaic") }</SidebarNotification>
            )
            : <SidebarSpinner />
            }
        </SidebarSection>
    );
};

export default InternalLinksSidebarSection;