import { __ } from '@wordpress/i18n';
import { useState, useEffect } from 'react';
import { dispatch, select } from '@wordpress/data';
import { useDispatch } from '@wordpress/data';
import { store as noticesStore } from '@wordpress/notices';
import {
    Dashicon,
    Flex,
    FlexItem,
    SelectControl,
    TextareaControl,
} from '@wordpress/components';
import Fetch from '../../../content-editor/helpers/fetch';
import GradientButton from '../../generate-image/components/gradient-button';
import DoubleRangeSlider from './double-range-slider';

const GenerateLeadsForm = ({
    attributes,
    setAttributes,
    manualMode,
}) => {
    const loadingOption = {
        value: '',
        label: __("Loading...", "seoaic"),
        disabled: true
    };
    const [companyServicesOptions, setCompanyServicesOptions] = useState([loadingOption]);
    const [targetAudienceOptions, setTargetAudienceOptions] = useState([loadingOption]);
    const [primaryGoalOptions, setPrimaryGoalOptions] = useState([loadingOption]);
    const [selectedCompanyService, setSelectedCompanyService] = useState('');
    const [selectedTargetAudience, setSelectedTargetAudience] = useState('');
    const [rangeMin, setRangeMin] = useState(5);
    const [rangeMax, setRangeMax] = useState(11);
    const [selectedPrimaryGoal, setSelectedPrimaryGoal] = useState('');
    const [leadsPrompt, setLeadsPrompt] = useState('');
    const [isGenerate, setIsGenerate] = useState(false);

    const editorDispatcher = dispatch('core/editor');
    const { createSuccessNotice, createWarningNotice } = useDispatch( noticesStore );
    const post = select('core/editor').getCurrentPost();
    const interval = 5;
    let timerId;

    const checkStatus = function(completeCallback) {
        const completeCallbackFunction = completeCallback || function() {};

        Fetch.get('leads-form/check-status', (response) => {
            if (response.data.data.status === 'complete') {
                completeCallbackFunction();

                if (response.data.data.done[post.id]) {
                    setIsGenerate(false);

                    setAttributes({
                        steps: response.data.data.done[post.id].content,
                        mode: manualMode,
                    });

                    editorDispatcher.autosave();
                    createSuccessNotice(__('Autosaved.', 'seoaic'), {
                        id: 'seoaic-autosaved',
                        isDismissible: true,
                        type: 'snackbar',
                    });

                } else {
                    console.error('[seoaic]: No ID in response:', response);

                    createWarningNotice(__('Something went wrong.', 'seoaic'), {
                        id: 'seoaic-request-failed',
                        isDismissible: true,
                        type: 'snackbar',
                    });
                }
            }
        });
    };

    const formGenerateCallback = (res) => {
        if (res.success) {
            timerId = setInterval(() => {
                checkStatus(() => { clearInterval(timerId); });
            }, interval * 1000);

            if (
                res.message
                && res.message.length
            ) {
                createSuccessNotice(res.message, {
                    id: 'seoaic-generate',
                    isDismissible: true,
                    type: 'snackbar',
                });
            }

        } else {
            setIsGenerate(false);

            if (
                res.message
                && res.message.length
            ) {
                createWarningNotice(res.message, {
                    id: 'seoaic-generate',
                    isDismissible: true,
                    type: 'snackbar',
                });
            }
        }
    };

    const generate = () => {
        setIsGenerate(true);
        const data = {
            post_id: post.id,
            company_service: selectedCompanyService ? Number(selectedCompanyService) + 1 : '',
            target_audience: selectedTargetAudience ? Number(selectedTargetAudience) + 1 : '',
            range_min: rangeMin,
            range_max: rangeMax,
            primary_goal: selectedPrimaryGoal,
            prompt: leadsPrompt,
        };

        Fetch.post('leads-form/generate', data, formGenerateCallback)
        .catch((err) => {
            setIsGenerate(false);
            console.error('[seoaic]:', err.message);

            createWarningNotice(__('Generation request failed', 'seoaic'), {
                id: 'seoaic-request-failed',
                isDismissible: true,
                type: 'snackbar',
            });
        });
    };

    const getSettingsCallback = (res) => {
        const data = res.data;
        const primaryGoal = data.primary_goal;

        setPrimaryGoalOptions(primaryGoal);
        setSelectedPrimaryGoal(primaryGoal[0].value);
        setLeadsPrompt(data.leads_form_prompt);

        if (
            data.services
            && data.services.length
        ) {
            const companyServicesArray = data.services.map((value, i) => ({
                value: i,
                label: value
            }));
            companyServicesArray.unshift({
                value: '',
                label: __("Select Company Service", "seoaic"),
                disabled: true
            });
            setCompanyServicesOptions(companyServicesArray);
        }

        if (
            data.target_audience
            && data.target_audience.length
        ) {
            const targetAudienceArray = data.target_audience.map((value, i) => ({
                value: i,
                label: value
            }));
            targetAudienceArray.unshift({
                value: '',
                label: __("Select Target Audience", "seoaic"),
                disabled: true
            });
            setTargetAudienceOptions(targetAudienceArray);
        }
    };

    const resetPostStatus = () => {
        Fetch.post('leads-form/reset-post-status', {
            post_id: post.id,
        }, formGenerateCallback)
        .catch((err) => {});
    };

    useEffect(() => {
        if ("generate" == attributes.mode) {
            Fetch.get('leads-form/generation-settings', getSettingsCallback)
            .catch((err) => {
                console.error('[seoaic]:', err.message);

                createWarningNotice(__('Request failed', 'seoaic'), {
                    id: 'seoaic-request-failed',
                    isDismissible: true,
                    type: 'snackbar',
                });
            });
        }
    }, []);

    return (
        isGenerate
        ? <Flex
            justify="center"
            align="center"
            gap={ 1 }
        >
            <FlexItem>
                <Dashicon
                    icon="admin-generic"
                    className="seoaic-gear-waiting-animate"
                />
            </FlexItem>
            <FlexItem>{ __("Generating...", "") }</FlexItem>
        </Flex>
        : <>
            <SelectControl
                label={ __('Company services:', 'seoaic') }
                value={ selectedCompanyService }
                onChange={ value => { setSelectedCompanyService(value) } }
                options={ companyServicesOptions }
            />
            <SelectControl
                label={ __('Target audience:', 'seoaic') }
                value={ selectedTargetAudience }
                onChange={ value => { setSelectedTargetAudience(value) } }
                options={ targetAudienceOptions }
            />
            <SelectControl
                label={ __('Leads Form primary goal:', 'seoaic') }
                value={ selectedPrimaryGoal }
                onChange={ value => { setSelectedPrimaryGoal(value) } }
                options={ primaryGoalOptions }
            />
            {
                "custom_interaction" == selectedPrimaryGoal
                && <TextareaControl
                    label={ __("Leads Form goal prompt:", "seoaic") }
                    rows={2}
                    value={ leadsPrompt }
                    onChange={ value => setLeadsPrompt(value) }
                />
            }
            <DoubleRangeSlider
                min={ 1 }
                max={ 15 }
                label={ __("Number of steps (range):", "seoaic") }
                rangeMin={ rangeMin }
                setRangeMin={ setRangeMin }
                rangeMax={ rangeMax }
                setRangeMax={ setRangeMax }
             />
            <GradientButton
                label={ __("Generate", "seoaic") }
                onClick={ generate }
            />
            <GradientButton
                label={ __("Reset Status", "seoaic") }
                onClick={ resetPostStatus }
                className="seoaic-dn"
            />
        </>
    );
};

export default GenerateLeadsForm;