import { Modal, SelectControl, Button, Flex } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useState, useEffect } from 'react';

const TranslateModal = (props) => {
    const [ languagesOptions, setLanguagesOptions] = useState([
        {
            label: 'Select language',
            value: ''
        }
    ]);

    useEffect( () => {
        apiFetch({
            headers: {
                'X-WP-Nonce': wpApiSettings.nonce
            },
            path: '/seoaic/v1/get-languages-options',
            method: 'POST',
            data: {},
        })
        .then((res) => {
            setLanguagesOptions(res.data.languages);
        }).catch((error) => {
            console.log('Error', error);
            noticesDispatcher.createErrorNotice(__('Error', 'seoaic'), {
                id: 'languages-error',
                isDismissible: false,
                type: 'snackbar',
            });
        });
    }, [] );

    function handleLanguageChange(value) {
        props.onLanguageChange(value);
    }

    return (
        <Modal title={ __('Translate Block', 'seoaic') } onRequestClose={ props.close }>
            <SelectControl
                label={ __('Language', 'seoaic') }
                value={ props.language.value }
                onChange={ handleLanguageChange }
                options={ languagesOptions }
                required
            />
            <Flex
                gap={2}
                align="center"
                justify="space-between"
            >
                <Button
                    variant="secondary"
                    onClick={ props.close }
                >{ __('Cancel', 'seoaic') }</Button>
                <Button
                    variant="primary"
                    onClick={ props.submit }
                >{ __('Submit', 'seoaic') }</Button>
            </Flex>
        </Modal>
    );
}

export default TranslateModal;