import { useState } from '@wordpress/element';
import { TextControl, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { testMailjetConnection, fetchMailjetLists } from '../utils/api';

const StepFour = ({ formData, updateFormData, setMailjetLists, setLoading, nextStep }) => {
    const [testing, setTesting] = useState(false);
    const [tested, setTested] = useState(false);
    const [testSuccess, setTestSuccess] = useState(false);

    const handleTest = async () => {
        if (!formData.api_key || !formData.api_secret) {
            alert(__('Please enter both API Key and API Secret', 'wpforms-mailjet-automation'));
            return;
        }

        setTesting(true);
        try {
            await testMailjetConnection(formData.api_key, formData.api_secret);
            setTestSuccess(true);
            setTested(true);
            
            // Automatically fetch lists after successful connection
            const lists = await fetchMailjetLists(formData.api_key, formData.api_secret);
            setMailjetLists(lists);
            
        } catch (error) {
            setTestSuccess(false);
            setTested(true);
            alert(__('Connection failed: ', 'wpforms-mailjet-automation') + error.message);
        } finally {
            setTesting(false);
        }
    };

    const handleNext = () => {
        if (!tested || !testSuccess) {
            alert(__('Please test your API connection first', 'wpforms-mailjet-automation'));
            return;
        }
        nextStep();
    };

    return (
        <div className="wpfmj-step">
            <h2>{__('Connect to Mailjet', 'wpforms-mailjet-automation')}</h2>
            <p className="description">
                {__('Enter your Mailjet API credentials. You can find these in your Mailjet account under Account Settings > REST API.', 'wpforms-mailjet-automation')}
            </p>

            <div className="wpfmj-field-group">
                <TextControl
                    label={__('API Key', 'wpforms-mailjet-automation')}
                    value={formData.api_key}
                    onChange={(value) => {
                        updateFormData('api_key', value);
                        setTested(false);
                    }}
                    type="text"
                    placeholder={__('Enter your Mailjet API Key', 'wpforms-mailjet-automation')}
                />
            </div>

            <div className="wpfmj-field-group">
                <TextControl
                    label={__('API Secret', 'wpforms-mailjet-automation')}
                    value={formData.api_secret}
                    onChange={(value) => {
                        updateFormData('api_secret', value);
                        setTested(false);
                    }}
                    type="password"
                    placeholder={__('Enter your Mailjet API Secret', 'wpforms-mailjet-automation')}
                />
            </div>

            <div style={{ marginBottom: '20px' }}>
                <Button
                    variant="secondary"
                    onClick={handleTest}
                    isBusy={testing}
                    disabled={testing || !formData.api_key || !formData.api_secret}
                >
                    {testing ? __('Testing...', 'wpforms-mailjet-automation') : __('Test Connection', 'wpforms-mailjet-automation')}
                </Button>
            </div>

            {tested && testSuccess && (
                <div className="wpfmj-alert wpfmj-alert-success">
                    {__('✓ Connection successful! Your Mailjet account is connected.', 'wpforms-mailjet-automation')}
                </div>
            )}

            {tested && !testSuccess && (
                <div className="wpfmj-alert wpfmj-alert-error">
                    {__('✗ Connection failed. Please check your credentials and try again.', 'wpforms-mailjet-automation')}
                </div>
            )}

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

export default StepFour;
