import { __ } from '@wordpress/i18n';
import FAQRepeater from './faq-repeater';
import GradientButton from '../../generate-image/components/gradient-button';

const FAQRepeaterBlock = ({
    attributes,
    setAttributes,
}) => {
    const questionTmpltObj = {
        'id': 0,
        'title': '',
        'content': ''
    };
    const questions = attributes.questions || [questionTmpltObj];

    const addNewFAQ = () => {
        setAttributes({ questions: [
            ...questions,
            {
                'id': questions[questions.length - 1].id + 1,
                'title': '',
                'content': ''
            }
        ] });
    };

    const removeFAQ = (id) => {
        let filteredQuestions = questions.filter((item) => {
            return id !== item.id;
        });

        if (!filteredQuestions.length) { // reset the last item to the default
            filteredQuestions = [questionTmpltObj];
        }

        setAttributes({ questions: filteredQuestions });
    };

    const updateFAQ = (values) => {
        setAttributes({ questions: values });
    };

    return (
        <>
            <FAQRepeater
                repeaterValues={ questions }
                updateRepeaterValues={ updateFAQ }
                removeFAQ={ removeFAQ }
            />
            <GradientButton
                icon="insert"
                label={ __("Add new FAQ", "seoaic") }
                onClick={ addNewFAQ }
            />
        </>
    );
};

export default FAQRepeaterBlock;