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

const MetaDescriptionSidebarSection = () => {
    const [ metaDescription, setMetaDescription ] = useState(null);
    const [ msg, setMsg ] = useState(null);
    const [ errorMsg, setErrorMsg ] = useState(null);
    const [ postId, setPostId ] = useState(null);
    const [ savedDescription, setSavedDescription ] = useState(null);
    const [ isButtonBusy, setIsButtonBusy ] = useState(false);

    const msgTimeout = 3000;

    const showHidingMsg = (msg, type='success') => {
        if ('success' == type) {
            setMsg(msg);
            setTimeout(() => {
                setMsg(null);
            }, msgTimeout);

        } else if ('error' == type) {
            setErrorMsg(msg);
            setTimeout(() => {
                setErrorMsg(null);
            }, msgTimeout);
        }
    };

    const processResults = (res) => {
        if (false === res.success) {
            setErrorMsg(res.message);

        } else if ("undefined" !== typeof res.data.meta_description) {
            setSavedDescription(res.data.meta_description);
            setMetaDescription(res.data.meta_description);

        } else {
            setErrorMsg('Something went wrong.');
        }
    };

    const errorFetchHandler = (res) => {
        setErrorMsg(res?.message ?? '');
        setIsButtonBusy(false);
    };

    const processSaveResults = (res) => {
        if (false === res.success) {
            showHidingMsg(res.message, 'error');

        } else {
            showHidingMsg(res.message);
        }

        setIsButtonBusy(false);
    };

    const saveDescription = () => {
        if (metaDescription != savedDescription) {
            const data = {
                description: metaDescription
            };

            setIsButtonBusy(true);
            setSavedDescription(metaDescription);

            Fetch.put('sidebar/' + postId + '/meta-description', data, processSaveResults, errorFetchHandler);
        }
    };

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

        setPostId(post.id);
        Fetch.get('sidebar/' + post.id + '/meta-description', processResults, errorFetchHandler);
    }, []);

    return (
        <SidebarSection
            title={ __("Meta Description", "seoaic") }
            id="meta_descriptions"
        >
            { null !== metaDescription
            ? (
                <>
                    <TextareaControl
                        label={ __("Meta Description", "seoaic") }
                        value={ metaDescription }
                        onChange={ (value) => {
                            setMetaDescription(value);
                        } }
                        rows={ 6 }
                    />
                    <Button
                        variant="primary"
                        onClick={ saveDescription }
                        disabled={ metaDescription == savedDescription }
                        isBusy={ isButtonBusy }
                    >
                        { __("Save", "seoaic") }
                    </Button>
                    {
                        null !== msg
                        && <SidebarNotification type="success">{ msg }</SidebarNotification>
                    }
                    {
                        null !== errorMsg
                        && <SidebarNotification type="error">{ errorMsg }</SidebarNotification>
                    }
                </>
            )
            : (
                null !== errorMsg
                ? (
                    <SidebarNotification type="error">{ errorMsg }</SidebarNotification>
                )
                : (
                    <SidebarSpinner />
                )
            ) }
        </SidebarSection>
    );
};

export default MetaDescriptionSidebarSection;