import { __ } from '@wordpress/i18n';
import { dispatch, useSelect, useDispatch } from '@wordpress/data';
import { useState, useEffect } from 'react';
import {
    RadioControl,
} from '@wordpress/components';
import { RichText } from '@wordpress/block-editor'
import ChoicesComponent from './answers-component';
import TopSpace from '../../multistep-lead-form/components/top-space';
import Fetch from '../../../content-editor/helpers/fetch';

const InteractiveArticleBlock = ({
    attributes,
    setAttributes,
    blockName,
    clientId,
}) => {
    const {
        getBlocks,
    } = useSelect('core/block-editor');
    const {
        getCurrentPost,
    } = useSelect('core/editor');
    const blocks = getBlocks();

    const [ answersStats, setAnswersStats ] = useState([]);

    const interactiveBlocks = blocks.filter((block) => {
        return block.name == blockName;
    });

    setAttributes({
        post_id: getCurrentPost().id,
    });

    if (!attributes.id) {
        for (let i = 0; i < interactiveBlocks.length; i++) {
            const block = interactiveBlocks[i];

            if (block.clientId == clientId) {
                setAttributes({
                    id: i + 1
                });
                break;
            }
        }
    }

    const answersTypesOptions = [
        { label: __('Single Choice (buttons)', 'seoaic'), value: 'single' },
        { label: __('Multi Choice (checkboxes)', 'seoaic'), value: 'multi' },
        { label: __('Open Text Field', 'seoaic'), value: 'textfield' },
    ];
    const interactiveBlocksOptions = [{
        label: __("Select interactive block", "seoaic"),
        value: '',
    }];

    const changeTypeHandler = (value) => {
        setAttributes({
            type: value,
            answers: []
        });
    };

    interactiveBlocks.forEach(block => {
        if (attributes.id != block.attributes.id) {
            interactiveBlocksOptions.push(
                {
                    label: '#' + block.attributes.id + ' - ' + (block.attributes.question ?? ''),
                    value: block.attributes.id,
                }
            );
        }
    });

    interactiveBlocksOptions.push({
        label: __('- Finish -', 'seoaic'),
        value: '#finish#',
    });

    useEffect(() => {
        if (attributes.id) {
            Fetch.get('interactive-article-stats/' + getCurrentPost().id + '/' + attributes.id, (res) => {
                if (
                    res.data
                    && res.data.stats
                    && Object.keys(res.data.stats).length !== 0
                ) {
                    setAnswersStats(res.data.stats);
                }
            })
            .catch((err) => {
                console.error('[seoaic]:', err.message);
            });
        }
    }, [attributes]);

    return (
        <div className="seoaic-interactive-article-block">
            <div className="seoaic-interactive-article-block-content">
                <div
                    className="seoaic-ia-id"
                >#{ attributes.id }</div>
                <RichText
                    tagName="div"
                    allowedFormats={ [] }
                    value={ attributes.question }
                    placeholder={ __('Question / Message', 'seoaic') }
                    onChange={ value => setAttributes({ question: value }) }
                    className="seoaic-ia-question"
                />
                <RadioControl
                    label={ __("Choices type", "seoaic") }
                    selected={ attributes.type }
                    options={ answersTypesOptions }
                    onChange={ value => changeTypeHandler(value) }
                    className="seoaic-ia-options-type"
                />
                <TopSpace>
                    <div className="seoaic-ia-block-form-wrapper">
                        <ChoicesComponent
                            attributes={ attributes }
                            setAttributes={ setAttributes }
                            answerType={ attributes.type }
                            interactiveBlocksOptions={ interactiveBlocksOptions }
                            answersStats={ answersStats }
                        />
                    </div>
                </TopSpace>
            </div>
        </div>
    );
};

export default InteractiveArticleBlock;