import { useEffect } from '@wordpress/element';
import { SelectControl, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { fetchFormFields } from '../utils/api';

const StepTwo = ({ formData, updateFormData, fields, setFields, setLoading, nextStep }) => {
    
    useEffect(() => {
        if (!formData.form_id || fields.length > 0) {
            return;
        }

        let cancelled = false;
        setLoading(true);

        fetchFormFields(formData.form_id)
            .then(data => {
                if (!cancelled) {
                    setFields(data);
                }
            })
            .catch(error => {
                if (!cancelled) {
                    alert('Error loading form fields: ' + error.message);
                }
            })
            .finally(() => {
                if (!cancelled) {
                    setLoading(false);
                }
            });

        return () => {
            cancelled = true;
        };
    }, [formData.form_id, fields.length, setFields, setLoading]);

    const handleNext = () => {
        if (!formData.field_mapping.email) {
            alert(__('Please select an email field', 'wpforms-mailjet-automation'));
            return;
        }
        nextStep();
    };

    const updateFieldMapping = (field, value) => {
        updateFormData('field_mapping', {
            ...formData.field_mapping,
            [field]: value
        });
    };

    const fieldOptions = [
        { label: __('Select a field...', 'wpforms-mailjet-automation'), value: '' },
        ...fields.map(field => ({
            label: field.label,
            value: field.id.toString()
        }))
    ];

    return (
        <div className="wpfmj-step">
            <h2>{__('Map Contact Fields', 'wpforms-mailjet-automation')}</h2>
            <p className="description">
                {__('Map your form fields to Mailjet contact properties. Email is required, while first name and last name are optional.', 'wpforms-mailjet-automation')}
            </p>

            <div className="wpfmj-field-group">
                <SelectControl
                    label={__('Email Field', 'wpforms-mailjet-automation') + ' *'}
                    value={formData.field_mapping.email}
                    options={fieldOptions}
                    onChange={(value) => updateFieldMapping('email', value)}
                    help={__('Required. This field will be used as the contact email address.', 'wpforms-mailjet-automation')}
                />
            </div>

            <div className="wpfmj-field-group">
                <SelectControl
                    label={__('First Name Field', 'wpforms-mailjet-automation')}
                    value={formData.field_mapping.firstname}
                    options={fieldOptions}
                    onChange={(value) => updateFieldMapping('firstname', value)}
                    help={__('Optional. If selected, this will populate the contact\'s first name in Mailjet.', 'wpforms-mailjet-automation')}
                />
            </div>

            <div className="wpfmj-field-group">
                <SelectControl
                    label={__('Last Name Field', 'wpforms-mailjet-automation')}
                    value={formData.field_mapping.lastname}
                    options={fieldOptions}
                    onChange={(value) => updateFieldMapping('lastname', value)}
                    help={__('Optional. If selected, this will populate the contact\'s last name in Mailjet.', 'wpforms-mailjet-automation')}
                />
            </div>

            <Button
                variant="primary"
                onClick={handleNext}
                style={{ marginTop: '20px' }}
            >
                {__('Next', 'wpforms-mailjet-automation')}
            </Button>
        </div>
    );
};

export default StepTwo;
